0

Given the following two strings

?room=any_characters123&name=John

?room=any_characters123

I want to extract "any_characters123" using regular expression.

I've tried

(?<=room=)(\w)+(?=\&)

but this one fails on the second string (because the matched string must end with "&").

How can I edit my regular expression so that it matches any_characters123 in both strings?

5 Answers 5

2

Since javascript won't support lookbehinds, you need to use capturing group.

\?room=(\w+)

Example:

> var s = "?room=any_characters123&name=John"
> var s1 = "?room=any_characters123"
undefined
> var re = /\?room=(\w+)/;
undefined
> console.log(re.exec(s)[1])
any_characters123
undefined
> console.log(re.exec(s1)[1])
any_characters123
Sign up to request clarification or add additional context in comments.

Comments

2

If you're using JS, lookbehind is not supported. You can modify the regex as follows:

room=([^&]+)

1 Comment

Amazingly this oldest correct answer remained without upvote +1
1

Try putting * in the end of your expression:

room=(\w+)\&*?

It will test for zero or plus ocurrences of &

Comments

0

This should do the trick:

/room=(\w+)&?/
/*
    find "room=" then match any word characters (at least one) until you
    possibly hit "&"
*/

Example:

/room=(\w+)&?/.test("?room=any_characters123")
// => true
"?room=any_characters123".match(/room=(\w+)&?/)
// => ["room=any_characters123", "any_characters123"]

Comments

0

Run the string through two regex tests, the one you already have, and then this one:

(?<=room=)(\w){1,}$

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.