Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Extract numbers after trigger sign from string variable

    Dear Statalist,
    I have the following data:

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str397 SHORTTITLE
    "Eine kurze discourse of the  the person of Prince Pi of Orange.Londorf, Thomas Dart para T. C. [=Thomas Chard] W. B. [=William Broome], 1882"              
    "Eine Erklärung of the queenes majestät will gegen den Überschuss of appLondorf, deputies Christopher Barker, 1887 (=1888)"                              
    "Ein wahrer Report des Erfolgs of Antwarpe zum Prinz von Parma, which was on the seaventeenth of august last past.Amsterdam (=England), Jacob Watleer, 1885"
    "von den drei ce qui s'est passé entre l'armee TurksLyon, Guichard Jullie et Tim Ammer, 1897 (=1898)."                                                      
    "Eine Veröffentlichung für den Kunden oder Subsudität all such sorts of silkss, wie von der Majestät bestätigt s ...London, Robert Barker, 1800 [=1801]"
    "Allergiesn und sterben göttlich legisInstrument ex sanctis et laudatis Autorensammlung Para , in ooffiziel Jos Bade, 1819 (=1820 n.s.)."                  
    end
    I would like to extract the year that is indicated after the “=” and generate a new variable called yearfix; I would like a missing value in case there is no “=XXXX”.

    For example:
    Yearfix
    .
    1888
    .
    1898
    1801
    1820


    Thank you very much!!!!!

    Best,
    Rike

  • #2
    Code:
    gen wanted = substr(SHORTTITLE , strpos(SHORTTITLE , "=1"), .)
    replace wanted= substr(wanted,2,4)
    destring wanted, replace

    Comment


    • #3
      You can also use a regular expression to match a "=" followed by 4 digits.

      Code:
      gen year = real(ustrregexs(1)) if ustrregexm(SHORTTITLE,"=([0-9]{4})")

      Comment


      • #4
        Dear Robert, Dear Andrew,

        thank you for your solutions. Both commands worked pretty well .
        I really appreciate your help!
        Best,
        Rike

        Comment

        Working...
        X