Announcement

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

  • Identify observations of a string variable which contain a pair of characters in a specific order

    I want to identify those observations of the string variable (x), which contain pair of characters "abs" and "def", in that order: i.e. if "abs" comes before "def".

    E.g. I want to identify the observation if x == "he walked to abs and def later" but not if x == "he walked to def and abs later" How can I do this? So far, I have used strpos(). I also posted a related question yesterday but posting a new question as this is a different question.

    Code:
     tab y if strpos(lower(y), "abs") & strpos (lower(y), "def")
    Many thanks,
    Mihir
    Last edited by Mihir Sharma; 19 Apr 2018, 10:56.

  • #2
    Code:
    gen abs_location = strpos(lower(y), "abs")
    gen def_location = strpos(lower(y), "def")
    tab y if (abs_location > 0) & (def_location > abs_location)

    Comment


    • #3
      Thank you Clyde!

      Comment


      • #4
        Just for the heck of it note also

        Code:
         
         ... if inrange(abs_location, 1, def_location - 1)
        it's not coding practice to be cryptic as a side-effect of being clever but that may be amusing. Even more amusing if I got it wrong.

        Comment


        • #5
          Waving the regular expression flag,
          Code:
          . * Example generated by -dataex-. To install: ssc install dataex
          . clear
          
          . input str30 y
          
                                            y
            1. "he walked to abs and def later"
            2. "he walked to def and abs later"
            3. "he walked to Abs and Def later"
            4. "he walked to zabsdefz later"
            5. end
          
          . list y if ustrregexm(y,"abs.*def",1), clean
          
                                              y  
            1.   he walked to abs and def later  
            3.   he walked to Abs and Def later  
            4.      he walked to zabsdefz later  
          
          .

          Comment


          • #6
            Thank you, everyone!

            Comment

            Working...
            X