Home > Software engineering >  regex - positive lookahead - spaces
regex - positive lookahead - spaces

Time:11-25

I am using Positive Lookahead and can´t clear 2 spaces before my lovely string with \s* because quantifier inside a lookbehind makes it non-fixed width.

I can do it easily with remove function in .Net but i just want to clear it with rgx.

The string is:

Propocet na CZK Kurz   1.00000  Per CZK.

Regex is:

(?<=[Kurz]\s)\s*\d*.\d*(?=\s*Per\s[EeCc][UuZz][RrKk])

Link: https://regex101.com/r/GaZKGB/1

There you can see spaces before number 1.00000, sometimes there is just one, sometimes more or less, and i want to clear it :)

Thanks!

CodePudding user response:

You can use

Kurz\s*\K\d (?:\.\d )?(?=\s*Per\s[EeCc][UuZz][RrKk])

See the regex demo.

Note:

  • [Kurz] matches r, z, u or K, not a Kurz as a sequence of chars
  • \K is a match reset operator that discards the text matched so far from the overall match memory buffer
  • An unescaped . matches any char, and to match a literal . you need to escape it.

Details:

  • Kurz - a word
  • \s* - zero or more whitespaces
  • \K - match reset operator
  • \d - one or more digits
  • (?:\.\d )? - an optional sequence of . and one or more digits
  • (?=\s*Per\s[EeCc][UuZz][RrKk]) - a positive lookahead that matches a location that is immediately followed with zero or more whitespaces, Per, a whitespace and then E or C, then U or Z and then R or K case insensitively.
  • Related