cheshire
cheshire

Reputation: 1159

Match everything after and before something regex Java

Here is my code:

    String stringToSearch = "https://example.com/excludethis123456/moretext";

    Pattern p = Pattern.compile("(?<=.com\\/excludethis).*\\/"); //search for this pattern 
    Matcher m = p.matcher(stringToSearch); //match pattern in StringToSearch

    String store= "";


    // print match and store match in String Store
    if (m.find())
    {
        String theGroup = m.group(0);
        System.out.format("'%s'\n", theGroup); 
        store = theGroup;
    }

    //repeat the process
    Pattern p1 = Pattern.compile("(.*)[^\\/]");
    Matcher m1 = p1.matcher(store);

    if (m1.find())
    {
        String theGroup = m1.group(0);
        System.out.format("'%s'\n", theGroup);
    }

I want to to match everything that is after excludethis and before a / that comes after.

With "(?<=.com\\/excludethis).*\\/" regex I will match 123456/ and store that in String store. After that with "(.*)[^\\/]" I will exclude / and get 123456.

Can I do this in one line, i.e combine these two regex? I can't figure out how to combine them.

Upvotes: 0

Views: 1660

Answers (3)

achAmh&#225;in
achAmh&#225;in

Reputation: 4266

If you don't want to use regex, you could just try with String::substring*

String stringToSearch = "https://example.com/excludethis123456/moretext";
String exclusion = "excludethis";
System.out.println(stringToSearch.substring(stringToSearch.indexOf(exclusion)).substring(exclusion.length(), stringToSearch.substring(stringToSearch.indexOf(exclusion)).indexOf("/")));

Output:

123456

* Definitely don't actually use this

Upvotes: 1

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

Just like you have used a positive look behind, you can use a positive look ahead and change your regex to this,

(?<=.com/excludethis).*(?=/)

Also, in Java you don't need to escape /

Your modified code,

String stringToSearch = "https://example.com/excludethis123456/moretext";

Pattern p = Pattern.compile("(?<=.com/excludethis).*(?=/)"); // search for this pattern
Matcher m = p.matcher(stringToSearch); // match pattern in StringToSearch

String store = "";

// print match and store match in String Store
if (m.find()) {
    String theGroup = m.group(0);
    System.out.format("'%s'\n", theGroup);
    store = theGroup;
}
System.out.println("Store: " + store);

Prints,

'123456'
Store: 123456

Like you wanted to capture the value.

Upvotes: 1

Derobukal
Derobukal

Reputation: 21

This may be useful for you :)

String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern pattern = Pattern.compile("excludethis([\\d\\D]+?)/");
Matcher matcher = pattern.matcher(stringToSearch);

if (matcher.find()) {
    String result = matcher.group(1);
    System.out.println(result);
}

Upvotes: 1

Related Questions