0

I have 3 different types of string in which I'm trying to match a pattern: Patterns:

  1. abcdedf_abc_abc_XS123456789_1234567
  2. abcdedf_abc_abc_AB_1234567_2014/03/17
  3. abcdef_abcdf_abc_xyz_12354AB12_1234567

In each case I'm tying to match '1234567'

The code that I have tried is:

m = re.search(r'_[0-9]+_|$',string)
m = re.search(r'_[0-9]+[_]|$',string)

None seem to be giving me the results that I want.

From http://docs.python.org/2/howto/regex.html I have read that:

"Alternation, or the “or” operator. If A and B are regular expressions, A|B will match any string that matches either A or B. | has very low precedence in order to make it work reasonably when you’re alternating multi-character strings. Crow|Servo will match either Crow or Servo, not Cro, a 'w' or an 'S', and ervo."

A and B must be regular expressions. I'm guessing that $ is not a regular expression.

3
  • I'm confused by the question. The code looks like you're searching for '_[0-9]+_|$' and not '123457'.
    – CodeMonkey
    Feb 14, 2014 at 1:26
  • The end result I'm looking for is 1234567. I'm using the _ at the start of the pattern b/c each time there is a 1234567 it is preceded by a _. So I strip the _ after I find a match.
    – WongSifu
    Feb 14, 2014 at 1:29
  • looks like @thefourtheye answered it. But he used an older version of python. You may need to use parentheses to print :-)
    – CodeMonkey
    Feb 14, 2014 at 1:33

1 Answer 1

3
strings = [
"abcdedf_abc_abc_XS123456789_1234567",
"abcdedf_abc_abc_AB_1234567_2014/03/17",
"abcdef_abcdf_abc_xyz_12354AB12_1234567"
]

import re
pattern = re.compile(r"(?<=_)\d+(?=_|$)")
for item in strings:
    print pattern.search(item).group()

Output

1234567
1234567
1234567

Regular expression visualization

Debuggex Demo

1
  • @WongSifu I included Debuggex demo in my answer. Please check that. If you have any question, please comment here :) Feb 14, 2014 at 1:37

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.