0

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.

2 Answers 2

2

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+\]).)*
Sign up to request clarification or add additional context in comments.

Comments

0

Another way could be matching the first [tr part with 1 or more comma separated digits, followed by repeatedly matching parts between square brackets that do not start with tr

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

The pattern matches

  • \[tr Match [tr
  • \d+(?:,\d+)+ Match 1+ digits and repeat 1+ times a comma and 1+ digits
  • ] Match a ] char
  • (?: Non capture group
    • \[(?!tr) Match [ and assert that it is not directly followed ty tr
    • [^][]+] Match from [ till ]
    • [^][]* Match 0+ times any char except [ and ]
  • )+ Close non capture group and repeat 1+ times

Regex demo

const s = '[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\d+(?:,\d+)+](?:\[(?!tr)[^\][\n]+][^\][\n]*)+/g;
console.log(s.match(regex));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.