0

I've a html tag in a string format. I need to fetch one dynamic value from that.

Input String :

final String str = "<input type=\"hidden\" name=\"OFBIZ_FRAMEWORK_REQUEST_SYNCH_TOKEN\" value=\"1590137573579\">\n";

From the above string I need to fetch the value attribute. (i.e, 1590137573579 - This value changes dynamically)

Below shared is the regex I tried, it is the giving the result but sure whether it is a proper regex or not.

String regex = "value=\"(.*?)\"";

Can some help here with proper regex statement.

user1869857
  • 27
  • 1
  • 9
  • 1
    Just to make the things simple. If you are trying to parse a html file then please look at the https://jsoup.org/ – UnknownBeast May 23 '20 at 06:07
  • I feel like the answers are focusing on the wrong things entirely really. OP already said it works for him. If anything needs changing there should be word boundaries around "value" to make sure it doesn't try to match on an attribute that ends with "value". Otherwise this regex is such a naive simple search, none of the proposed changes really matter. – user120242 May 23 '20 at 07:54
  • 1
    [Don't parse html with regex](https://stackoverflow.com/a/1732454/2235972) – denvercoder9 May 23 '20 at 16:01

3 Answers3

1

Your regex needs 38 steps to match the value, Demo.

If the value is always a number, you can use:

String regex = "value=\"(\d*)\"";

It needs 12 steps Demo

If value can contain any character but double quote, use:

String regex = "value=\"([^\"]*)\"";

It also needs 12 steps Demo

Toto
  • 89,455
  • 62
  • 89
  • 125
0
String regex = "value=\\\"(.*?)\\\"";

You may try to escape both the backslash symbol (\) and the quote symbol (").

zhugen
  • 240
  • 3
  • 11
0

Try this :

import java.util.regex.*;

public class RegexTest {

    public static void main(String args[]){

        final String str = "<input type=\"hidden\" name=\"OFBIZ_FRAMEWORK_REQUEST_SYNCH_TOKEN\" value=\"1590137573579\">\n";

        String regex = "value=\\\"(.*?)\\\"";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
}
Amit kumar
  • 2,169
  • 10
  • 25
  • 36