Reputation: 423
I have string regex
"product_default_shipping_cost:\['(.*)'"
and string
"product_sale_price:['19.99'], product_default_shipping_cost:['1.99'], product_type:['Newegg']"
and i want get only 1.99
.
My code :
Pattern pattern = Pattern.compile(regex_string);
Matcher m = pattern.matcher(html);
while (m.find()) {
for (int i = 1; i <= groupCount; i++) {
Log.w(TAG,m.group(i));
}
}
But i have got 1.99'], product_type:['Newegg']
Strange that it regular expression works perfectly in python and SWIFT but not java. I can not change this regular. What could be the issue and how to fix it?
P.S i really can't change this regular, it takes dynamic
Upvotes: 1
Views: 93
Reputation: 98921
You're using a greedy
regex .*
, try using a non greedy, also know as lazy
, by appending a ?
, i.e.:
product_default_shipping_cost:\['(.*?)'\]
Pattern pattern = Pattern.compile("product_default_shipping_cost:\['(.*?)'\]");
Matcher m = pattern.matcher(html);
while (m.find()) {
for (int i = 1; i <= groupCount; i++) {
Log.w(TAG,m.group(i));
}
}
DEMO
https://regex101.com/r/aF1hI6/1
Nice explanation about greedy and lazy regex
Upvotes: 1
Reputation: 12440
.*
will match as many characters as possible (is "greedy").
You can either use non-gready .*?
, or limit what can be matched: [^']*
.
Upvotes: 2
Reputation: 2834
Try changing it to this:
product_default_shipping_cost:\['(.*?)'
.*?
is lazy and will only try to match up to the first '
Upvotes: 2