Reputation: 4236
I have a string which contains multiple ip addresses like so:
String header = "Received: from example.google.com ([192.168.0.1]) by example.google.com ([192.168.0.2]) with mapi; Tue, 30 Nov 2010 15:26:16 -0600";
I want to use regular expression to get both IP's from this. I so far my code looks like this
public String parseIPFromHeader(String header) {
Pattern p = Pattern.compile("\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b");
Matcher m = p.matcher(header);
boolean matchFound = m.find();
System.out.println(matchFound);
if (matchFound) {
// Get all groups for this match
for (int i=0; i<=m.groupCount(); i++) {
// Get the group's captured text
String groupStr = m.group(i);
// Get the group's indices
int groupStart = m.start(i);
int groupEnd = m.end(i);
// groupStr is equivalent to
System.out.println(header.subSequence(groupStart, groupEnd));
}
}
}
but I never get match. Am I approaching this correctly? Thanks
Upvotes: 0
Views: 2806
Reputation: 41
If you only need the IP adresses you can greatly simplify your regex to match just those
"([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})" //not perfect, i know...
And then use Matcher.find() multiple times to find all occurences in the string
while(m.find()) {
String ip = m.group(1) //the first group is at index 1, group 0 is the whole match. (Does not actually make any difference here)
}
Upvotes: 0
Reputation: 1265
You escaped \
characters before dots, but if i remember correcly, you need escape it in \b
sequence too, so replace them with \\b
Upvotes: 6