2

I am trying to find a certain string with RegEx. I want to find "something starting with 'f' and ending with first 2" (it must contain only one 2). In this example I want to find result = "fdba12" but the code at below is giving me 'fdba12312' (containing two 2). How can I stop searching when I find 2 immediately?

import re
string2 = "asfdba12312 sssdr1 12şljş1 kf"

t = re.findall(r'[f][\w]*[2]', string2 )
print(t)
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
abidinberkay
  • 1,857
  • 4
  • 36
  • 68

1 Answers1

1

The problem is that your regex contains a \w* pattern that can also match the adjoining 2 pattern. There are 2 ways to achieve what you need: 1) using a lazy quantifier suggested by rock321987, and 2) use a reverse shorthand char class inside a negated character class [^...] and also negate 2.

Thus, use

f[^\W2]*2

See the regex demo

The [^\W2]* pattern matches zero or more characters other than non-word characters (so, it matches all word characters) and those other than 2.

Note: greedy matching is faster than lazy matching here.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563