Home > Software engineering >  regex capture if not in a certain pattern
regex capture if not in a certain pattern

Time:03-01

I am trying to write a regex to match numbers that ends with ' and are not in the pattern \d \s*/\s*\d '

x1 = "Better: 6 ' only"
x2 = """Better stain 15/16" 11/12\'"""
x3 = "14 / 16' 5' only"
x4 = "35' 14/15' better"
lst = [x1,x2,x3,x4]

expected output

x1 -> 6
x2 -> None
x3 -> 5
x4 -> 35

this is what I have so far (?<!\d/)(\d \s*\')

Any help is appreciated

CodePudding user response:

You can use a capture group with an alternation.

The match before the pipe gets out of the way what you don't want to match, then after the pipe you can capture what you want to keep, which in this case is 1 or more digits followed by '

\d \s*/\s*\d '|(\d )\s*'
  • \d \s*/\s*\d '
  • | Or
  • (\d )\s*' Capture 1 digits in group 1 followed by optional whitespace chars and '

regex demo

  • Related