sureshd
sureshd

Reputation: 565

In regular expression, how to match a string with optional string

My regular expression is

\/(.*)\/(((?:opt1)?)((?:\/opt2)?)((?:\/opt3))?)?\/data\/(.*)

In the above expression, I'm considering /opt1/opt2/opt3 as optional where all can be present or either one or two.

My desired output is below strings should match

But only /main/opt1/data/sample.txt is getting matched. Also below string's should not match

What is the problem here. Thanks

Upvotes: 1

Views: 610

Answers (2)

rock321987
rock321987

Reputation: 11032

A much simpler way will be to use

^\/[^\/]*(?:\/opt[123])*\/data\/.+$
   <---->
Replace with main
  if necessary

Regex Demo

Regex Breakdown

^ #Starting of string
\/ #Match / literally
[^\/]* #Match anything except /
(?:\/opt[123])* #Match opt followed by 1, 2 or 3
\/ #Match / literally
data #Match data literally
\/ #Match / literally
.+ #From last / to end of string
$ #End of string

You can also define range if required for only 0 to 3 occurence

^\/[^\/]*(?:\/opt[123]){0,3}\/data\/.+$

If the order matters, then you can use

^\/main(?:\/opt1)?(?:\/opt2)?(?:\/opt3)?\/data\/.+$

Regex Demo

Upvotes: 3

Andrew
Andrew

Reputation: 7880

This simple regular expression seems to do the trick, it works fine with your test strings:

\/main(\/opt[123])*\/data\/.+

If your input string won't contain any other character, you can also add the anchors to specify begin and end:

^\/main(\/opt[123])*\/data\/.+$

Upvotes: 1

Related Questions