Home > OS >  Regex to match what's before or after a character in different situations
Regex to match what's before or after a character in different situations

Time:10-13

I have some troubles writing a regex

What I want to achieve, I want to match the following string 6.62 X 25.250755 L but only what is after the X character or there may be cases when I have to match the following string 25.250755 X 6.62 in this case I need to match what's before the X character and the final case is when I have something like this: 25.250755 L X 6.62 or 25.250755L X 6.62 (with or without space, with or without the L character)

This is what I have so far, but is not enough and I don't know how to continue form here on

/[Xx]([\s\S]*)$/gm

CodePudding user response:

([0-9]*[.])?[0-9] ?L? X ([0-9]*[.])?[0-9] ?L? should work.

CodePudding user response:

For your example data, you can repeat a group with a capture group to capture the value of the last iteration.

(?: ?\b(\d (?:\.\d )) ?[XL]) \b
  • (?: Non capture group
    • ?\b Match an optional space and a word boundary
    • ( Capture group 1
      • \d (?:\.\d ) Match 1 or more digits with an optional decimal part
    • ) Close group 1
    • ?[XL] Match an optional space and either X or L
  • ) Close the non capture group and repeat it 1 or more times
  • \b A word boundary

Regex demo

  • Related