0

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

3
  • You've already fully (over-)specified the IP digit pattern, so there's no point in forcing \b anchors. Commented Nov 29, 2011 at 16:07
  • ahhh thanks! that did the trick, well at least I am getting matches., is there anyway I can get both? like loop through the matches? It seems to only find the first one. Commented Nov 29, 2011 at 16:08
  • 1
    There is a point to the \bs, without them (part of) 1234.1.1.1234 would match. Commented Nov 29, 2011 at 16:14

2 Answers 2

6

You escaped \ characters before dots, but if i remember correcly, you need escape it in \b sequence too, so replace them with \\b

Sign up to request clarification or add additional context in comments.

Comments

0

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.