Navnath
Navnath

Reputation: 1094

Single regex to find string between two strings or started with single string only

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

Answers (2)

Raman Sahasi
Raman Sahasi

Reputation: 31841

You can use

id=[^&]*&?

DEMO

  1. id= our required key
  2. [^&]* capture everything that follows BUT ampersand &.
  3. &? if ampersand follows, then capture it, otherwise dont. ? indicates that it's optional.

Upvotes: 1

anubhava
anubhava

Reputation: 784888

You can use this regex to capture id=... value followed by & or line end:

(?<=[?&])id=[^&]*(?:&|$)

RegEx Demo

  • (?<=[?&]) 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 end

Full match will be:

  1. id=iuyu1223-uhs12& - case I
  2. id=iuyu1223-uhs12 - case II

Upvotes: 3

Related Questions