0

I want to extract the value 5342test behind the name="buddyname" from a fieldset tag. But there are multiple fieldsets in the HTML code. Below the example of the string in the HTML.

<fieldset style="display:none"><input type="hidden" name="buddyname" value="5342test" /></fieldset>

I have some difficulties to put in the different patterns in Pattern.compile and i just want the value 5342test displayed not the other results, could somebody please help? Thank you.

My code:

String stringToSearch = "5342test";

            Pattern pattern = Pattern.compile("(\\value=\\})");  
            Matcher m = pattern.matcher(stringToSearch);

            while (m.find())
            {
              // get the matching group
              String codeGroup = m.group(1);

              // print the group
              System.out.format("'%s'\n", codeGroup); // should be 5342test
            }
Lars
  • 915
  • 4
  • 18
  • 27

2 Answers2

1

Use this pattern:

Pattern pattern = Pattern.compile("<input[^>]*?value\\s*?=\\s*?\\\"(.*?)\\\"");
Andrei LED
  • 2,560
  • 17
  • 21
  • Hi Andrei,First of all thank you but i get an error in eclipse in this section (.*?)\\")" of your example. – Lars Sep 25 '11 at 11:33
  • It says Syntac errors on tokens, delete these tokens. Thx for reviewing. – Lars Sep 25 '11 at 11:41
  • I did not exactly put in your example, my mistake ;) but still got an error. LogCat: 09-25 13:53:49.090: WARN/System.err(3120): java.util.regex.PatternSyntaxException: Syntax error U_REGEX_MISMATCHED_PAREN near index 36: 09-25 13:57:35.091: WARN/System.err(3341): ]*?value\s*?=\s*?\"(.*?)\") – Lars Sep 25 '11 at 11:56
  • Oops, my bad. Remove extra closing parenthesis. – Andrei LED Sep 25 '11 at 14:18
  • To match a quotation mark (`"`) all you need is `\"`, not `\\\"`. It only needs to be escaped because it's in a string literal; it has no special meaning for the regex. – Alan Moore Sep 28 '11 at 08:13
0

Since you want the input values inside a fieldset tag, you can use this regex pattern.

Pattern pattern = Pattern.compile("<fieldset[^>]*>[^<]*<input.+?value\\s*=\\s*\\\"([^\\\"]*)\\\"");
Matcher matcher = pattern.matcher("<fieldset style=\"display:none\"><input type=\"hidden\" name=\"buddyname\" value=\"5342test\" /></fieldset>");
if (matcher.find()) 
    System.out.println(matcher.group(1)); //this prints 5342test
else
    System.out.println("Input html does not have a fieldset");
Narendra Yadala
  • 9,554
  • 1
  • 28
  • 43