java 如何使用正则表达式匹配正斜杠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40038575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:52:43  来源:igfitidea点击:

How to match the forward slash using regex

javaregex

提问by vinoth.mohan

How to use regex to detect and has the forward slash in path. Also with numbers

如何使用正则表达式来检测路径中的正斜杠。还有数字

Example String str = "/urpath/23243/imagepath/344_licensecode/" I want to use regex to make sure the path is match for numbers with forward slash. the format match must like this "/23243/"

示例字符串 str = "/urpath/23243/imagepath/344_licensecode/" 我想使用正则表达式来确保路径与带有正斜杠的数字匹配。格式匹配必须像这样“/23243/”

Any idea guys?

有什么想法吗?

Thanks

谢谢

回答by Zabuzard

You need to escape the special character /by using \. However, \also is the escaping character used by Java, but you want to pass the symbol itself to Regex, so it escapes for Regex. You do so by escaping the escape symbol with \\. So in total you will have \\/for the slash.

你需要躲避特殊字符/使用\。然而,\也是Java使用的转义字符,但是你想把符号本身传递给Regex,所以它转义为Regex。您可以通过使用 转义转义符来实现\\。所以总的来说,你将拥有\\/斜线。

Use this snippet:

使用这个片段:

String input = ...
Pattern pattern = Pattern.compile("\/23243\/");
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
    System.out.println("Does match!");
} else {
    System.out.println("Does not match!");
}

You can try the Regex itself at regex101: regex101/RkheRs

您可以在regex101尝试 Regex 本身:regex101/RkheRs

回答by vinoth.mohan

I found my answer.Thanks to Mgaert

我找到了答案。感谢 Mgaert

List<String> listArray = new ArrayList<String>();
listArray.add(file.getCanonicalPath());

// Regular expression in Java to check if String is number or not
Pattern pattern = Pattern.compile("/\d+/");
for (String path: listArray) {
    // Match patter for numbers path
    Matcher matcher = pattern.matcher(path);
    if (matcher.find()) {
        System.out.println("Does match!"+ path);
    } else {
        System.out.println("Does Not match!");
    }
}