簡體   English   中英

不起作用正則表達式

[英]Doesn't work regular expression

我有字符串正則表達式
"product_default_shipping_cost:\\['(.*)'"

和弦

"product_sale_price:['19.99'], product_default_shipping_cost:['1.99'], product_type:['Newegg']"

而且我只想得到1.99 我的代碼:

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));
   }
}

但是我有1.99'], product_type:['Newegg']奇怪的是,它的正則表達式在python和SWIFT中完美運行,但在java中卻沒有。 我不能更改此常規。 可能是什么問題以及如何解決?

附言:我真的不能更改此常規,它需要動態

嘗試將其更改為此:

product_default_shipping_cost:\['(.*?)'

.*? 很懶,只會嘗試匹配第一個'

.*將匹配盡可能多的字符(“貪心”)。

您可以使用非預備.*? ,或限制可匹配的內容: [^']*

您使用的是greedy正則表達式.* ,請嘗試使用非貪婪 ,也被稱為lazy ,通過附加一個? ,即:

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));
   }
}

演示

https://regex101.com/r/aF1hI6/1


關於貪婪和懶惰的正則表達式的很好的解釋

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM