Reputation: 6254
I have some text with heading string and set of letters. I need to get first one-digit number after set of string characters.
Example text:
ABC105001
ABC205001
ABC305001
ABCD105001
ABCD205001
ABCD305001
My RegEx:
^(\D*)(\d{1})(?=\d*$)
Link: http://www.regexr.com/390gv
As you cans see, RegEx works ok, but it captures first groups in results also. I need to get only this integer and when I try to put ?=
in first group like this: ^(?=\D*)(\d{1})(?=\d*$)
, Regex doesn't work.
Any ideas?
Thanks in advance.
Upvotes: 0
Views: 417
Reputation: 89557
(?=..)
is a lookahead that means followed by and checks the string on the right of the current position.
(?<=...)
is a lookbehind that means preceded by and checks the string on the left of the current position.
What is interesting with these two features, is the fact that contents matched inside them are not parts of the whole match result. The only problem is that a lookbehind can't match variable length content.
A way to avoid the problem is to use the \K
feature that remove all on the left from match result:
^[A-Z]+\K\d(?=\d*$)
Upvotes: 2
Reputation: 2995
try:
^(?:\D*)(\d{1})(?=\d*$) // (?: is the beginning of a no capture group
Upvotes: 1
Reputation: 4840
You're trying to use a positive lookahead when really you want to use non-capturing groups.
The one match you want will work with this regex:
^(?:\D*\d{1})(\d*)$
The (?:
string will start a non-capturing group. This will not come back in matches.
So, if you used preg_match(';^(?:\D*\d{1})(\d*)$;', $string, $matches)
to find your match, $matches[1]
would be the string for which you're looking. (This is because $matches[0]
will always be the full match from preg_match
.)
Upvotes: 1