在线测试器中的正则表达式匹配,但在JAVA中没有

时间:2021-08-19 18:10:27

I'm trying to extract the text BetClic from this string popup_siteinfo(this, '/click/betclic', '373', 'BetClic', '60€');

我正在尝试从这个字符串popup_siteinfo中提取文本BetClic(这,'/ click / betclic','373','BetClic','60€');

I wrote a simple regex that works on Regex Tester but that doesn't work on Java.

我写了一个简单的正则表达式,适用于Regex Tester,但不适用于Java。

Here's the regex

这是正则表达式

'\d+', '(.*?)'

here's Java output

这是Java输出

Exception in thread "main" java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Matcher.java:485)
at javaapplication1.JavaApplication1.main(JavaApplication1.java:74)
Java Result: 1

and here's my code

这是我的代码

Pattern pattern = Pattern.compile("'\\d+', '(.*?)'");
Matcher matcher = pattern.matcher(onMouseOver);                
System.out.print(matcher.group(1));

where the onMouseOver string is popup_siteinfo(this, '/click/betclic', '373', 'BetClic', '60€');

其中onMouseOver字符串是popup_siteinfo(this,'/ click / betclic','373','BetClic','60€');

I'm not an expert with regex, but I'm quite sure that mine isn't wrong at all!

我不是正则表达式的专家,但我很确定我的一点也不错!

Suggestions?

建议?

2 个解决方案

#1


3  

You need to call find() before group(...):

你需要在group(...)之前调用find():

Pattern pattern = Pattern.compile("'\\d+', '(.*?)'");
Matcher matcher = pattern.matcher(onMouseOver);                
if(matcher.find()) {
  System.out.print(matcher.group(1));
}
else {
  System.out.print("no match");
}

#2


0  

You're calling group(1) without having first called a matching operation (such as find()).- which is the cause of IllegalStateException.

你没有先调用匹配操作(例如find())来调用group(1).-这是IllegalStateException的原因。

And if you have to use that grouped cases for replacement then this isn't needed if you're just using $1 since the replaceAll() is the matching operation.

如果您必须使用该分组的情况进行替换,那么如果您只使用$ 1,则不需要这样做,因为replaceAll()是匹配操作。

#1


3  

You need to call find() before group(...):

你需要在group(...)之前调用find():

Pattern pattern = Pattern.compile("'\\d+', '(.*?)'");
Matcher matcher = pattern.matcher(onMouseOver);                
if(matcher.find()) {
  System.out.print(matcher.group(1));
}
else {
  System.out.print("no match");
}

#2


0  

You're calling group(1) without having first called a matching operation (such as find()).- which is the cause of IllegalStateException.

你没有先调用匹配操作(例如find())来调用group(1).-这是IllegalStateException的原因。

And if you have to use that grouped cases for replacement then this isn't needed if you're just using $1 since the replaceAll() is the matching operation.

如果您必须使用该分组的情况进行替换,那么如果您只使用$ 1,则不需要这样做,因为replaceAll()是匹配操作。