Search code examples
javascriptregexregex-group

Finding the right Regular Expressions in JavaScript


Having hard time finding the correct regex in JavaScript.

this is the test string

[tr1,1,70,18][jl2]39th St [nl1]Adams Blvd [tr71,1,39,18][jl3]$0.70[nl1]$0.80[tr1,19,110,8][jl3]HOV2+ W/FLEX $0

and I'd like to find an expression that matches all of the 3 string below:

[tr1,1,70,18][jl2]39th St [nl1]Adams Blvd 

[tr71,1,39,18][jl3]$0.70[nl1]$0.80

[tr1,19,110,8][jl3]HOV2+ W/FLEX $0

I managed to get close with this regex which matches the [tr portions but need the rest of the text as well.

\[tr\d+,\d+,\d+,\d+\]

regex tester here.


Solution

  • If there's nothing starts with [tr other than the beginning of the group, you may try this regex:

    \[tr(?:(?!\[tr).)*
    
    • \[tr starting with [tr
    • (?:(?!\[tr).)* matching every character after it unless there's an another [tr ahead

    const text = '[tr1,1,70,18][jl2]39th St [nl1]Adams Blvd [tr71,1,39,18][jl3]$0.70[nl1]$0.80[tr1,19,110,8][jl3]HOV2+ W/FLEX $0';
    
    const regex = /\[tr(?:(?!\[tr).)*/g;
    
    const result = text.match(regex);
    
    console.log(result);

    Or you can try this one for safer choice:

    \[tr\d+,\d+,\d+,\d+\](?:(?!\[tr\d+,\d+,\d+,\d+\]).)*