匹配regex Java前后的所有内容

  • 本文关键字:regex Java 匹配 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

我可以在一行中完成这项操作吗,即将这两个正则表达式组合起来?我不知道如何把它们组合起来。

就像你使用了积极的向后看一样,你可以使用积极的向前看,并将你的正则表达式更改为

(?<=.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

就像你想捕捉价值一样。

这可能对您有用:)

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

如果您不想使用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

*绝对不要实际使用这个

最新更新