Reputation: 9875
I have some regular expressions in Python which I need to convert to java. I know what I want the regular expression to do, but I just don't know how to convert it.
Here is the expression in python: ^172\.(1[6789]|2\d|30|31)\.
. I want it to capture any sort of ip address like 172.X
where X ranges from 16 to 31.
This works in python:
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)
and it appropriately captures what I expect:
['19']
['24']
[]
['19']
But I tried to convert these to java and itdoesn't work. It seems like I should be able to convert to a java regex simply by adding a \
to each \
to escape correctly? like ^172\\.(1[6789]|2\\d|30|31)\\.
but it is still not matching the way I want. what am I missing about the differences between python and JAVA regular expression in this case?
I do not have the java
code easily available, but I tried this tool: http://java-regex-tester.appspot.com/, and I set the Target Text to 172.19.0.0
and it doesn't match, but it does "Find". However, when I input "blah" as the Target Text it ALSO puts something in the "Find" section...so I'm not sure I trust this tool http://java-regex-tester.appspot.com/ because it puts any string in "find", even when it is "blah".
So, how do I verify that my java regular expression is correct?
Upvotes: 0
Views: 2559
Reputation: 159135
Java 8 does not have the equivalent of findall()
, so you need to write your own find()
loop and gather the results into a List
, like this:
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);
}
Output
[19]
[24]
[]
[19]
Or course, since your regex can find at most one match, your code should really be:
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();
}
Output
19
24
19
Upvotes: 2