2017-04-17 268 views
-2

我有一些Python正则表达式,我需要转换为java。我知道我想要正则表达式做什么,但我不知道如何转换它。如何将python正则表达式转换为java正则表达式?

以下是python中的表达式:^172\.(1[6789]|2\d|30|31)\.。我希望它捕获任何有点像172.X IP地址,其中X的范围从16到31

这个作品在蟒:

import re 
pattern='^172\\.(1[6789]|2\\d|30|31)\\.' 
test_strings = ['172.19.0.0', '172.24.0.0', '172.45.0.0', '172.19.98.94'] 
for string in test_strings: 
    print re.findall(pattern, string) 

,并适当地抓住我的期望:

['19'] 
['24'] 
[] 
['19'] 

但我试图将这些转换为java,它不工作。看来我应该能够转换为java正则表达式,只需将\添加到每个\即可正确转义?像^172\\.(1[6789]|2\\d|30|31)\\.

但它仍然不符合我想要的方式。在这种情况下,我错过了python和JAVA正则表达式之间的区别?

我没有java代码容易获得,但我想这个工具:http://java-regex-tester.appspot.com/,我设定目标文本172.19.0.0和不匹配,但它确实“查找”。但是,当我输入“blah”作为目标文本时,它也会在“查找”部分放入某些东西...所以我不确定我是否相信这个工具http://java-regex-tester.appspot.com/,因为它将任何字符串放在“查找”中,即使它是“嗒嗒”。

那么,如何验证我的java正则表达式是否正确?

+2

“但它仍然是不匹配的方式我想:”我们可以看到你究竟是如何使用这个表达式在Java中?你的意见是什么,预期的和实际的结果? – Pshemo

+0

我们可以看看它是如何在python中使用的吗? –

+0

*猜测:*您正在使用'matches()'。不要,因为它总是与*整个*输入匹配。使用['find()'](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#find--)。 – Andreas

回答

1

的Java 8不具备的findall()等价,所以你需要编写自己的find()循环,结果收集到List,像这样:

Pattern pattern = Pattern.compile("^172\\.(1[6789]|2\\d|30|31)\\."); 
String[] test_strings = {"172.19.0.0", "172.24.0.0", "172.45.0.0", "172.19.98.94"}; 
for (String string : test_strings) { 
    List<String> list = new ArrayList<>(); 
    for (Matcher matcher = pattern.matcher(string); matcher.find();) 
     list.add(matcher.group(1)); 
    System.out.println(list); 
} 

输出

[19] 
[24] 
[] 
[19] 

或当然,因为你的正则表达式可以找到最多一个匹配,你的代码应该是:

Pattern pattern = Pattern.compile("^172\\.(1[6789]|2\\d|30|31)\\."); 
String[] test_strings = {"172.19.0.0", "172.24.0.0", "172.45.0.0", "172.19.98.94"}; 
for (String string : test_strings) { 
    Matcher matcher = pattern.matcher(string); 
    if (matcher.find()) 
     System.out.println(matcher.group(1)); 
    else 
     System.out.println(); 
} 

输出

19 
24 

19 
+0

我并不年龄投票,但+1 @Andreas!对于'scala'也是如此? – jaja

+0

@jaja您应该仍然可以通过点击复选标记来接受答案。对不起,我不认识斯卡拉。 – Andreas

相关问题