ria
ria

Reputation: 7974

Regular expression for either or matching

I have a string which could end with either

"/"

or

"/?secure=true"

I need to validate it. I tried this

\b(/(/?secure=true)?)\b

but I get no matches found with the regex. However, with

^(/(\$secure=true)?)$

match is found. But this wont help in my case as the string that I want to validate will be prefixed with chars something like "thisismystring/" or "thisismystring/?secure=true".

I want to know how to go about this.

Upvotes: 1

Views: 1988

Answers (3)

Sufian Latif
Sufian Latif

Reputation: 13356

Can be done like this:

/(\?secure=true)?$

Upvotes: 1

ixx
ixx

Reputation: 32273

Both cases would contain the

/

So that should not be in the optional part.

You put the optional part in ()?

and escape the question mark with backslash

/(\?secure=true)?

And to indicate that it should end with that, you put $ at the end

/(\?secure=true)?$

Upvotes: 4

David M
David M

Reputation: 72850

You need to use the pipe symbol (|) to specify an or:

(/|/\?secure=true)$

You also need to escape the question mark, as here, and should specify the "$" for end of string but not the "^" for start of string.

Upvotes: 6

Related Questions