Retrieve part of string from one word to another or to the end

Bohdan Maliar :

I have a following lines in my file:

/rootfolder/test/a/b/c/magicword/blabla
/rootfolder/test/a/b/c

All these lines should match a regex pattern. In addition, I need to find a group between /rootfolder and /magicword or if there is no /magicword - till the end. So, for my two lines above, the 1st group should be /test/a/b/c.

I have tried /rootfolder(?|(?>(/.*)(?>/magicword).*)|(/.*)) (with escaping of /). It works well for some online regex validators, but so far no luck to use it in Java.

Is there any chance to make such regular expression using Java? Thanks in advance!

Edit: Example of working regex: https://regex101.com/r/cJkIJH/1 . The same result I need in Java.

Edit2: Thanks to the answers below look like /rootfolder(.*?)(?:/magicword.*|$) works perfectly for my conditions.

anubhava :

You don't need anything fancy here just use this regex and work with capture group #1:

/rootfolder(.*?)(?:/magicword.*|$)

RegEx Demo

Non-capturing group (?:/magicword.*|$) matches end of line or /magicword and rest of line after .*? (lazy match).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328349&siteId=1