[英]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. 我想匹配excludethis
之后和/
之后的所有内容。
With "(?<=.com\\\\/excludethis).*\\\\/"
regex I will match 123456/
and store that in String store
. 使用"(?<=.com\\\\/excludethis).*\\\\/"
正则表达式,我将匹配123456/
并将其存储在String store
。 After that with "(.*)[^\\\\/]"
I will exclude /
and get 123456
. 之后用"(.*)[^\\\\/]"
排除/
并得到123456
。
Can I do this in one line, ie combine these two regex? 我可以在一行中执行此操作,即将这两个正则表达式合并吗? I can't figure out how to combine them. 我不知道如何合并它们。
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);
}
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 /
另外,在Java中,您无需转义/
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. 就像您想抓住价值一样。
If you don't want to use regex
, you could just try with String::substring
* 如果您不想使用regex
, 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("/")));
Output: 输出:
123456 123456
* Definitely don't actually use this * 绝对不要实际使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.