Home > Net >  Extract text before first \sx\s with regex
Extract text before first \sx\s with regex

Time:10-27

I have text like this:

#12222223334 x $32.97

I want to extract the last number of the number before the "x" for example in this case the number 4.

Another example: #8885555889 x $33.33. Here, the number I want is 9.

I tried ^(. ?) x, but its all the number before the x.

CodePudding user response:

this also gets you the last digits before the space and x

https://regex101.com/r/zVevtY/1

(\d)\s?x

# (\d) : capture a digit
# \s? : before a possible white space
# x : followed by literal x

CodePudding user response:

If your regex engine support lookaheads, you may use:

\d(?=\s*x\s \$\d (?:\.\d )?$)

Demo

This pattern says to match:

  • \d a single digit
  • (?= assert that what follows (but do not match)
    • \s*x\s x
    • \$\d (?:\.\d )? followed by a currency amount
    • $ end of the string
  • ) end lookahead
  • Related