יום שישי, 21 ביוני 2013

Ruby and Regex

Play with regex in ruby

  1: theStrToCheck = "I have found 164  elephants in my garden last week. my email is loveme42@hotmail.com "
  2: thePos = (/elephants/ =~ theStrToCheck)
  3: puts  thePos
  4: puts theStrToCheck 
  5: 


returns 18 if no match return nothing.

  1: theStrToCheck = "I have found 164  elephants in my garden last week. my email is loveme42@hotmail.com */ "
  2: thePos = (/ \*\// =~ theStrToCheck)
  3: puts  thePos

returns 84 note about the \ to follow special characters.

  1: theStrToCheck = "I have found 164  elephants in my garden last week.next 164  my email is loveme42@hotmail.com */ "
  2: thePosOfNumber = (/\d\d\d/ =~ theStrToCheck)
  3: puts  thePosOfNumber
  4: 
  5: thePosOfNumber = (/(\d){2} / =~ theStrToCheck)
  6: puts  thePosOfNumber
  7: 
  8: puts theStrToCheck

The results are 13 , 14
The first match sequence of  3 digits
The second match 2 digits with space after them.

אין תגובות:

הוסף רשומת תגובה