这可能很简单,但我对regex非常陌生,我需要在字符串中执行一些regex匹配并提取其中的数字。下面是我使用示例i/p和必需的o/p的代码。我试图通过引用Pattern来构造https://www.freeformatter.com/java-regex-tester.html,但是regex匹配本身是返回false。
Pattern pattern = Pattern.compile(".*/(a-b|c-d|e-f)/([0-9])+(#[0-9]?)");
String str = "foo/bar/Samsung-Galaxy/a-b/1"; // need to extract 1.
String str1 = "foo/bar/Samsung-Galaxy/c-d/1#P2";// need to extract 2.
String str2 = "foo.com/Samsung-Galaxy/9090/c-d/69"; // need to extract 69
System.out.println("result " + pattern.matcher(str).matches());
System.out.println("result " + pattern.matcher(str1).matches());
System.out.println("result " + pattern.matcher(str1).matches());以上所有SOP都返回false。我使用的是java 8,在一条语句中是否有任何方法可以匹配模式,然后从字符串中提取数字。
如果有人能告诉我如何调试/开发regex.Please,我会很高兴的--如果我的问题中有什么不清楚,请随时告诉我。
发布于 2018-10-23 09:22:21
你可以用
Pattern pattern = Pattern.compile(".*/(?:a-b|c-d|e-f)/[^/]*?([0-9]+)");当与matches()一起使用时,上面的模式不需要显式锚点、^和$。
详细信息
.* -除换行字符以外的任何0+字符,尽可能多/ -最右边的/,后面跟着后续的子模式(?:a-b|c-d|e-f) -一个非捕获组,与内部的任何替代方案相匹配:a-b、c-d或e-f。/ -a / char[^/]*? -除/以外的任何字符,尽可能少([0-9]+) -第1组:一个或多个数字。List<String> strs = Arrays.asList("foo/bar/Samsung-Galaxy/a-b/1","foo/bar/Samsung-Galaxy/c-d/1#P2","foo.com/Samsung-Galaxy/9090/c-d/69");
Pattern pattern = Pattern.compile(".*/(?:a-b|c-d|e-f)/[^/]*?([0-9]+)");
for (String s : strs) {
Matcher m = pattern.matcher(s);
if (m.matches()) {
System.out.println(s + ": \"" + m.group(1) + "\"");
}
}使用相同正则表达式的替换方法添加了锚:
List<String> strs = Arrays.asList("foo/bar/Samsung-Galaxy/a-b/1","foo/bar/Samsung-Galaxy/c-d/1#P2","foo.com/Samsung-Galaxy/9090/c-d/69");
String pattern = "^.*/(?:a-b|c-d|e-f)/[^/]*?([0-9]+)$";
for (String s : strs) {
System.out.println(s + ": \"" + s.replaceFirst(pattern, "$1") + "\"");
}输出:
foo/bar/Samsung-Galaxy/a-b/1: "1"
foo/bar/Samsung-Galaxy/c-d/1#P2: "2"
foo.com/Samsung-Galaxy/9090/c-d/69: "69"发布于 2018-10-23 09:25:10
因为您总是匹配regex中的最后一个数字,所以我只想在这个regex .*?(\d+)$中使用replaceAll:
String regex = ".*?(\\d+)$";
String strResult1 = str.replaceAll(regex, "$1");
System.out.println(!strResult1.isEmpty() ? "result " + strResult1 : "no result");
String strResult2 = str1.replaceAll(regex, "$1");
System.out.println(!strResult2.isEmpty() ? "result " + strResult2 : "no result");
String strResult3 = str2.replaceAll(regex, "$1");
System.out.println(!strResult3.isEmpty() ? "result " + strResult3 : "no result");如果结果为空,则没有任何数字。
输出
result 1
result 2
result 69发布于 2018-10-23 09:25:19
下面是使用String#replaceAll的一行程序
public String getDigits(String input) {
String number = input.replaceAll(".*/(?:a-b|c-d|e-f)/[^/]*?(\\d+)$", "$1");
return number.matches("\\d+") ? number : "no match";
}
System.out.println(getDigits("foo.com/Samsung-Galaxy/9090/c-d/69"));
System.out.println(getDigits("foo/bar/Samsung-Galaxy/a-b/some other text/1"));
System.out.println(getDigits("foo/bar/Samsung-Galaxy/9090/a-b/69ace"));
69
no match
no match这适用于您提供的示例输入。请注意,我添加了逻辑,这将显示no match的情况下,结束数字不能匹配适合您的模式。在不匹配的情况下,通常会留下原始输入字符串,而输入字符串并不是所有数字。
https://stackoverflow.com/questions/52945410
复制相似问题