0

I want to capture all occurrences of a letter, followed by a digit, but no letter before the above letter. So, there is a f9 match in f9, 3f9, f99, but not in af9. I have the following regex: ([^a-z]|^)([a-z])(\d).

Why doesn't it match both f9 and x0 in f9x0 and how to achieve this? It matches only f9. In f9 x0 there are two matches.

Thank you.

Paul R
  • 2,631
  • 3
  • 38
  • 72

2 Answers2

1

There is no character before the x but you require one. You are looking for a lookbehind:

(?:^|(?<![a-z]))[a-z]\d

See a demo on regex101.com.

Jan
  • 42,290
  • 8
  • 54
  • 79
1

As you asked it:
"capture all occurrences of a symbol, followed by a digit, but no symbol before the above symbol"

/(?<=\d|^)\w\d/g

Match:

f9      >> f9
f9x0    >> f9, x0
af9    
3f9     >> f9

Regex101.com demo

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • @AndrewFount first of your regex has too many matching groups making the result quite odd: https://regex101.com/r/h07ed8/1 - Secondly the option `^`(*start of string*) in ([^a-z]|^) already **matched and consumed** the first match `f9` - and will not proceed further to `x0`. – Roko C. Buljan May 15 '21 at 13:33
  • First capture is `f9` (with the start of the string). The second match should be `9x0`. It doesn't work because `9` is already captured, correct? – Paul R May 15 '21 at 13:48
  • @AndrewFount Yes. If by contrast you use a non-consuming Positive Lookbehind `(?<=` the thing will work as intended for the next group `x0` as well. – Roko C. Buljan May 15 '21 at 14:03