假设我有一个数字序列
1 2 3 4 1 2 3 4
正如你所看到的,这里有一个循环:
1 2 3 4
现在我正在尝试创建一个正则表达式来匹配模式。该模式可以是序列长度的一半或 2 个数字长。这就是我到目前为止所拥有的
Pattern cycle = Pattern.compile("((\\d+\\s)+(\\d+\\s))\\1");
给我一串由空格分隔的数字。我正在尝试使用捕获组但不理解它。有什么帮助吗?
最佳答案
你可以使用这个:
(\d(?:\s+\d)+)\s+\1
这将匹配由空格分隔的两个或多个数字,捕获它并查找在另一个空格字符之后捕获的内容:
( # begin capturing group
\d # a digit, followed by
(?: # begin non capturing group
\s+ # one or more space characters, followed by
\d # a digit
)+ # end non capturing group, repeated once or more,
) # end capturing group `\1`, followed by
\s+ # one or more spaces, followed by
\1 # the exact content of the first captured group
注意:它假设重复中的间距完全相同!
关于Java正则表达式查找数字模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14120260/