Regex to match around delimiters

Viewed 59

Using the string

A B x C x D - E x F

I am trying to capture the groups A B C and D but not E or F.

My understanding of regex is that I want everything before \sx\s up to the \s-\s,

so I would start with .*(?=\sx\s),

which I want to happen as many times until I reach the \s-\s.

My result is (.*(?=\sx\s))*.*(?=\s-\s) which returns A B x C x D.

I think this may have to do with the way lookaheads work but I am lost on what to change.

1 Answers

Using a positive lookahead (?=\s-\s), the pattern must be present in the data.

If you want to match AB, C and D and also want to match those values if this part - E x F is not present, you could make use of a quantifier in a negative lookbehind:

(?<!\s-\s.*)[A-Z](?:\s[A-Z])*

Explanation

  • (?<!\s-\s.*) Negative lookbehind, assert what is on the left is not \s-\s
  • [A-Z] Match a char A-Z
  • (?: Non capture group
    • \s[A-Z] Math whitespace char followed by A-Z
  • )* Close group and repeat 0+ times

.NET regex demo

Related