Home > front end >  Regex capture group that excludes a group
Regex capture group that excludes a group

Time:11-12

Here is the test string:

[x] Package - Front and Rear align, rotate and balance 4 wheels ------------------- $105.00

I want to capture multiple groups as follows:

  • Group 1: Open square bracket, 0-3 characters then close bracket
  • Group 2: Longest text that excludes --
  • Group 3: Longest text that has only -
  • Group 4: remainder

Here's my failed attempt

^(\[.{0,3}\])(. (?!.*--.*))(-*)(.*)$

Also I do not have access to lookbehind if that makes a difference.

CodePudding user response:

You can use

^(\[[^][]{0,3}])\s*(.*?)\s*(-- )\s*(.*)

See the regex demo.

Details:

  • ^ - start of string
  • (\[[^][]{0,3}]) - Group 1: a [ char, then zero to three occurrences of any chars other than [ and ] and then a ] char
  • \s* - zero or more whitespaces
  • (.*?) - Group 2: any zero or more chars other than line break chars as few as possible
  • \s* - zero or more whitespaces
  • (-- ) - Group 3: a hyphen and then one or more hyphens
  • \s* - zero or more whitespaces
  • (.*) - Group 4: any zero or more chars other than line break chars as many as possible.
  • Related