Gurkirat Singh
Gurkirat Singh

Reputation: 33

How to find Substring in Java using Regular Expression?

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?

Upvotes: 0

Views: 142

Answers (1)

JvdV
JvdV

Reputation: 75920

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]);

Upvotes: 3

Related Questions