tags:

views:

74

answers:

1

Hi all,

I have a string as below:

"http:172.1." = (10, 1,3);

"http:192.168." = (15, 2,6);

"http:192.168.1.100" = (1, 2,8);

The string inside " " is a Tag and inside () is the value for preceding tag. What is the regular expression that will return me: Tag: http:172.1. Value: 10, 1,3

+1  A: 

This regex

"([^\"]*)"\s*=\s*\(([^\)]*)\)*.

returns the text between quotes "" as group 1, and the text in parentheses () as group 2.

NB: when saving this as a string, you will have to escape the quote characters and double the slashes. It becomes unreadable very quickly - like this:

"\"([^\\\"]*)\"\\s*=\\s*\\(([^\\)]*)\\)*."

EDIT: As requested, here's an example use:

   Pattern p = Pattern.compile("\"([^\\\"]*)\"\\s*=\\s*\\(([^\\)]*)\\)*.");
   // put p as a class member so it's computed only once...

   String stringToMatch = "\"http://123.45\" = (0,1,3)";
   // the string to match - hardcoded here, but you will probably read 
   // this from a file or similar
   Matcher m = p.matches(stringToMatch);
   if (m.matches()) {
      String url = p.group(1);    // what's between quotes
      String value = p.group(2);   // what's between parentheses
      System.out.println("url: "+url);   // http://123.45
      System.out.println("value: "+value); // 0,1,3
   }

For more details, see the Sun Tutorial - Regular Expressions.

mdma
can you give me a short implementation, i am new in java
chitresh
sure - there's one added to my answer.
mdma