尽管matches()为真,但是正则表达式捕获组仍无法识别group(1) [英] Regex capturing group doesn't recognise group(1) despite matches() true

查看:160
本文介绍了尽管matches()为真,但是正则表达式捕获组仍无法识别group(1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java写一些简单的(我认为是)正则表达式,以删除星号或&号,该星号或&号直接出现在某些标点符号旁边。
$ b

I'm writing some simple (I thought) regex in Java to remove an asterisk or ampersand which occurs directly next to some specified punctuation.
This was my original code:

String ptr = "\\s*[\\*&]+\\s*";
String punct1 = "[,;=\\{}\\[\\]\\)]"; //need two because bracket rules different for ptr to left or right
String punct2 = "[,;=\\{}\\[\\]\\(]";

out = out.replaceAll(ptr+"("+punct1+")|("+punct2+")"+ptr,"$1");

除了删除字符串的 ptr部分外,还删除了punct!(即,将匹配的字符串替换为空字符串)

我通过以下操作进行了进一步检查:

Which instead of just removing the "ptr" part of the string, removed the punct too! (i.e. replaced the matched string with an empty string)
I examined further by doing:

String ptrStr = ".*"+ptr+"("+punct1+")"+".*|.*("+punct2+")"+ptr+".*";
Matcher m_ptrStr = Pattern.compile(ptrStr).matcher(out);

并发现:

m_ptrStr.matches() //returns true, but...
m_ptrStr.group(1) //returns null??

我不知道我在做错什么,因为在使用复杂得多的正则表达式和group(1)总是返回捕获的组之前,我已经使用了这种精确方法。一定有我没有的东西。没发现,所以..有什么想法吗?

I have no idea what I'm doing wrong as I've used this exact method before with far more complicated regex and group(1) has always returned the captured group. There must be something I haven't been able to spot, so.. any ideas?

推荐答案

问题是您在每一侧都有一个捕获组的替代方案:

The problem is that you have an alternation with a capturing group on each side:

(regex1)|(regex2)

匹配器将启动并搜索匹配项使用第一个交替;

The matcher will start and search for a match using the first alternation; if not found, it will try the second alternation.

但是,它们仍然是两个组,只有一个会匹配。

However, those are still two groups, and only one will match. The one which will not match will return null, and this is what happens to you here.

因此,您需要同时测试这两个组;如果不匹配,则返回null。由于您有匹配项,因此至少一个不会为空。

You therefore need to test both groups; since you have a match, at least one will not be null.

这篇关于尽管matches()为真,但是正则表达式捕获组仍无法识别group(1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆