在java中的模式匹配中重用消耗的字符?
考虑以下模式:-
aba
接下来。源字符串:-
abababbbaba
01234567890 //Index Positions
使用 java.util.regex 包中的 Pattern 和 Matcher 类,仅查找此模式两次,因为 regex 不考虑已使用的字符。
如果我想重复使用部分已消耗的字符怎么办?也就是说,我想要在这里匹配 3 个匹配项,一个在位置 0,一个在位置 2(之前被忽略),一个在位置 8。
我该怎么做?
Consider the following Pattern :-
aba
And the foll. source string :-
abababbbaba
01234567890 //Index Positions
Using Pattern and Matcher classes from java.util.regex package, finds this pattern only two times since regex does not consider already consumed characters.
What if I want to reuse a part of already consumed characters. That is, I want 3 matches here, one at position 0, one at 2 (which is ignored previously), and one at 8.
How do I do it??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你可以使用 indexOf() 类似的东西。
打印:
0、2 和 8
I think you can use the indexOf() for something like that.
Prints:
0, 2 and 8
您可以使用前瞻来实现这一点。现在您拥有的是
group(1)
中的第一个位置和group(2)
中的第二个匹配项。两者都使您正在搜索的句子中的每个字符串的长度为 3。输出:
您可以跳过
最终字符串提示
部分,这只是为了向您展示它匹配的内容和位置。You can use a look ahead for that. Now what you have is the first position in
group(1)
and the second match ingroup(2)
. Both making each String of length 3 in the sentence you are searching in.Output:
You can skip the
final String hint
part, this is just to show you what it matches and where.如果您可以更改正则表达式,那么您可以简单地使用如下内容:
If you can change the regexp, then you can simply use something like: