I have java string like https://example.com?id=iuyu1223-uhs12&event=update
So I want to get string between id
and &
including id
and &
. But in some cases &
might not present like https://example.com?id=iuyu1223-uhs12
, so need to select full string till end. I am using regex (SAAS_COMMON_BASE_TOKEN_ID.*?&)
. It's working with first string but fails for second one. Can we have or condition in regex so that I will get result like id=iuyu1223-uhs12&
or id=iuyu1223-uhs12
Asked
Active
Viewed 907 times
1
-
See [Java regular expression OR operator](http://stackoverflow.com/questions/2031805/java-regular-expression-or-operator). – Wiktor Stribiżew Mar 03 '17 at 07:35
2 Answers
3
You can use this regex to capture id=...
value followed by &
or line end:
(?<=[?&])id=[^&]*(?:&|$)
(?<=[?&])
is lookbehind that asserts we have?
or&
beforeid=
id=[^&]*
will matchid=
followed by 0 or more characters till before hit&
(?:&|$)
matches&
or line end
Full match will be:
id=iuyu1223-uhs12&
- caseI
id=iuyu1223-uhs12
- caseII
-
It's absolutely working fine with string regex which you have shared. I just removed acceptance mark because of complexity. Solution which you provided is able to handle all cases but for me, this level of complex case will not be there. Thanks Anubhava. – Navnath Mar 07 '17 at 05:09
-
Ok thanks for your comment and giving your reasons. You should just keep in mind that these questions and answers will be read and used by so many programmers facing similar problems in future so it is better to cover all the cases. – anubhava Mar 07 '17 at 05:17
1
You can use
id=[^&]*&?
id=
our required key[^&]*
capture everything that follows BUT ampersand&
.&?
if ampersand follows, then capture it, otherwise dont.?
indicates that it's optional.

Raman Sahasi
- 30,180
- 9
- 58
- 71
-
-
@anubhava I included positive lookahead in [original version of answer](http://stackoverflow.com/revisions/42573175/1) but then realized that it was making it too much complicated as such a parameter was not there in url and so removed it. – Raman Sahasi Mar 03 '17 at 11:55