Preg_match PHP 到 Java 的翻译
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13013695/
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
Preg_match PHP to java translation
提问by Evilsithgirl
I am having some trouble converting a php pregmatch to java. I thought I had it all correct but it doesn't seem to be working. Here is the code:
我在将 php pregmatch 转换为 java 时遇到了一些麻烦。我以为我一切都正确,但它似乎不起作用。这是代码:
Original PHP:
原始PHP:
/* Pattern for 44 Character UUID */
$pattern = "([0-9A-F\-]{44})";
if (preg_match($pattern,$content)){
/*DO ACTION*/
}
My Java code:
我的Java代码:
final String pattern = "([0-9A-F\-]{44})";
public static boolean pregMatch(String pattern, String content) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(content);
boolean b = m.matches();
return b;
}
if (pregMatch(pattern, line)) {
//DO ACTION
}
So my test input is: DBA40365-7346-4DB4-A2CF-52ECA8C64091-0
所以我的测试输入是:DBA40365-7346-4DB4-A2CF-52ECA8C64091-0
Using a series of System.outs I get that b = false.
使用一系列 System.outs 我得到 b = false。
回答by doublesharp
To implement a function as you did in your code:
要像在代码中那样实现功能:
final String pattern = "[0-9A-F\-]{44}";
public static boolean pregMatch(String pattern, String content) {
return content.matches(pattern);
}
And then you can call it as:
然后你可以称之为:
if (pregMatch(pattern, line)) {
//DO ACTION
}
You don't need the parenthesis in your pattern
because that just creates a match group, which you are not using. If you need access to back references, you would need the parenthesis an a more advanced regex code using Pattern
and Matcher
classes.
您不需要括号,pattern
因为它只会创建一个您没有使用的匹配组。如果您需要访问反向引用,您将需要括号使用Pattern
和Matcher
类的更高级的正则表达式代码。
回答by xdazz
You could just use String.matches()
你可以用 String.matches()
if (line.matches("[0-9A-F-]{44}")) {
// do action
}