Home > Mobile >  Angular Regex Split String 1x asd..... 2x asd
Angular Regex Split String 1x asd..... 2x asd

Time:02-20

I am trying to split a string by [0-9] [xX] | [0-9] [xX], string example:

10 x source 4 50° on booms (2 downstage left and right, 2 upstage left and right) 2x festoons (mentioned above) 4x 1kx Fresnel backlight in L712 4x SL 15/32 (3x L443, 4x R119) – all four of which are specifically focused specials 1x Edison bulb suspended from grid

I would like to break the text into seperate lines using a pipe in angular, to display like:

10 x source 4 50° on booms (2 downstage left and right, 2 upstage left and right)
2x festoons (mentioned above)
4x 1kx Fresnel backlight in L712
4x SL 15/32 (3x L443, 4x R119) – all four of which are specifically focused specials
1x Edison bulb suspended from grid

I have tried to use the following regex but it is including the next 1x in the regex.

/([0-9] [xX] [a-zA-z].*)(?:([0-9] [xX]))/gm
Output: 10x source 4 50° on booms (2 downstage left and right, 2 upstage left and right) 2x festoons (mentioned above) 4x 1kx Fresnel backlight in L712 4x SL 15/32 (3x L443, 4x R119) – all four of which are specifically focused specials 1x

I would also like to be able to add the option as mentioned in the first sentance to check on two scenarios.

  1. 1x asd....
  2. 1 x asd....

Then I will split the string using the regex in Angular.

CodePudding user response:

You can use

/\d \s*x\b(?:\([^()]*\)|[^()])*?(?=\d x|$)/gi

See the regex demo. Details:

  • \d - one or more digits
  • \s* - zero or more whitespaces
  • x\b - x and a word boundary
  • (?:\([^()]*\)|[^()])*? - zero or more (but as few as possible) sequences of a ( zero or more chars other than ( and ) ) or any char but ( and )
  • (?=\d x|$) - a positive lookahead that matches a location that is immediately followed with one or more digits and x or end of string.

See the JavaScript demo:

const text = "10 x source 4 50° on booms (2 downstage left and right, 2 upstage left and right) 2x festoons (mentioned above) 4x 1kx Fresnel backlight in L712 4x SL 15/32 (3x L443, 4x R119) – all four of which are specifically focused specials 1x Edison bulb suspended from grid";
const re = /\d \s*x\b(?:\([^()]*\)|[^()])*?(?=\d x|$)/gi;
document.body.innerHTML = "<pre>"   JSON.stringify(text.match(re), 0, 4)   "</pre>"

  • Related