0

I have a String called String mainString = "/abc/def&ghi&jkl"; I need to find the substring using Regex in java. The Substring will be lastindexof("/") and indexof("&") i.e. def. How can I do that using Regular Expression in java?

0

1 Answer 1

3

Maybe something like:

(?<=\/)(?=[^\/]*$).*?(?=&)
  • (?<=\/) - Positive lookbehind to match positions that are right after a forward slash.
  • (?=[^\/]*$) - Positive lookahead with a negated character class to match anything but a forward slash zero or more times followed by the end string position.
  • .*? - Match any character other than newlinge zero or more times but lazy (read up to the next).
  • (?=&) - Positive lookahead to match position in string that is followed by a &.

See the Online Demo

Note: You may swap the positive lookahead for a negative lookahead as mentioned by @CarySwoveland: (?<=\/)(?!.*\/).*?(?=&). See the demo


A second option is using a capture group (as per @TheFourthBird):

/([^/&]+)&[^/]*$

Where:

  • / - Match a literal forward slash.
  • ( - Open capture group.
    • [^/&]+ - A negated character class matching anything other than forward slash or ampersand at least once.
    • ) - Close capture group.
  • & - A literal ampersand.
  • [^/]* - A negated character class, matching anything other than forward slash zero or more times.
  • $ - End string ancor.

See the Online Demo


Also I am not sure you'd need regular expressions at all. I've no experience with Java whatsoever but pieced this together with some googling:

public class Tst{    
     public static void main(String []args){
        String mainString = "/abc/def&ghi&jkl";
        String[] bits = mainString.split("/");
        String subbit = bits[bits.length-1].split("&")[0];
        System.out.print(subbit);
     }
}

Which returns: def

Note: Or even as a one-liner with nested split commands: System.out.print(mainString.split("/")[mainString.split("/").length - 1].split("&")[0]);

Sign up to request clarification or add additional context in comments.

3 Comments

...or, in place of your first lookahead, (?!.*\/).
Yes @CarySwoveland, thats maybe even a little faster? I've added it in =) Thanks for mentioning it.
Or perhaps also use a capturing group /([^/&]+)&[^/]*$ regex101.com/r/LMk0Vd/1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.