Reputation: 1094
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
Upvotes: 1
Views: 911
Reputation: 31841
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.Upvotes: 1
Reputation: 784888
You can use this regex to capture id=...
value followed by &
or line end:
(?<=[?&])id=[^&]*(?:&|$)
(?<=[?&])
is lookbehind that asserts we have ?
or &
before id=
id=[^&]*
will match id=
followed by 0 or more characters till before hit &
(?:&|$)
matches &
or line endFull match will be:
id=iuyu1223-uhs12&
- case I
id=iuyu1223-uhs12
- case II
Upvotes: 3