0

I'm trying to get a value from an HTML page that has the name "this" ex:

name="this" value="XXXX-XXX-xxxxx-xxxxx"

I tried to use

Pattern pat = Pattern.compile("name=\"this\" value=\"(.*?)\"");
Matcher match = pat.matcher(sb);
        if(match.matches())
            return match.group();

But nothing returned. What should I do?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
wtsang02
  • 18,603
  • 10
  • 49
  • 67
  • 4
    http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – Crozin Jul 01 '12 at 17:06
  • 1
    Either `find` or `matches("(?s)^.*name=\"this\" value=\"(.*?)\".*$");` where `(?s)` (DOTALL) accepts newlines for the dot (.). **matches() is for a matching of the entire text.** – Joop Eggen Jul 01 '12 at 17:09

2 Answers2

1

Like Joop said; use "find":

Pattern pat = Pattern.compile("name=\"this\" value=\"(.*?)\"");
Matcher match = pat.matcher(sb);
if(match.find())
    return match.group(1);

Also note that you'll want to retrieve "group(1)", since just group() returns the entire pattern match.

Terje Mikal
  • 938
  • 6
  • 16
0

I think you should consider more conditions , like

name = "this" id = "something" value = 'xxx'

Then your pattern wouldn't meet the requirements such as space between "name" and "=" 'xxx' and string between attribute "name" and attribute "value", so I think the pattern should be like the following form:

private final String matchString = "name\\s*=\\s*(?:\"this\")|(?:'this')" +
                                    ".*?" +
                                    "value\\s*=\\s*" +
                                    "(?:\"([^\"]*)\") |(?: '([^']*)')";
private final Pattern pattern = Pattern.compile(matchString,Pattern.DOTALL|Pattern.COMMENTS); 
Matcher matcher = pattern.matcher(content);

    while(matcher.find())
    {
        System.out.println(matcher.group(1));
    }

At the same time , the tip from up floor is needed!

ohyeahchenzai
  • 314
  • 3
  • 13