匹配正则表达式Java前后的所有内容

时间:2019-01-30 15:44:11

标签: java regex

这是我的代码:

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

我想匹配excludethis之后和之后的/之前的所有内容。

使用"(?<=.com\\/excludethis).*\\/"正则表达式,我将匹配123456/并将其存储在String store中。之后,使用"(.*)[^\\/]",我将排除/并得到123456

我可以一行执行此操作,即将这两个正则表达式结合起来吗?我不知道如何合并它们。

3 个答案:

答案 0 :(得分:1)

这可能对您有用:)

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

答案 1 :(得分:1)

就像在正面使用正面表情一样,您可以在正面使用正面表情并将正则表达式更改为此,

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

此外,在Java中,您无需转义/

您修改的代码,

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

打印

'123456'
Store: 123456

就像您想获取价值一样。

答案 2 :(得分:1)

如果您不想使用regex,则可以尝试使用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("/")));

输出:

  

123456

* 绝对不实际使用此