开发者

Whats the regular expression for finding string between " "

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 in开发者_Go百科side () is the value for preceding tag. What is the regular expression that will return me: Tag: http:172.1. Value: 10, 1,3


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜