user1398498
user1398498

Reputation: 429

RegExp: match a string separated by semicolons at start or between semicolons or at the end of the string

Given these strings:

1;2;3
2;1;3
2;3;1

I need to match/find the 1 in it (for the sake of simplicity, the 1 can be any string).

Came up with this pattern as a partial solution, which at the moment suits my needs (because it returns true on regexp.test()):

(?:^|;)(1)(?=;|$)

It matches all the ocurrences of 1 but:

the second and the third result has the semicolon attached in front of it like this:

;1

How could I rewrite the pattern to get rid of the semicolon?

Thanks in advance!

Upvotes: 1

Views: 657

Answers (3)

Andynedine
Andynedine

Reputation: 441

Try this regex:

^([^1]*)1([^1]*)*$

If I use your cases, it works!! This url can help you: http://www.metriplica.com/es/recursos/expresiones-regulares

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336468

You can't - JavaScript doesn't support lookbehind assertions which you'd need for this.

But you can simply access match[1] to get the contents of the first capturing group of your regex match object.

Upvotes: 1

Maksim Gladkov
Maksim Gladkov

Reputation: 3079

Just use regexp.match()[1] to get what you want.

Upvotes: 1

Related Questions