[英]Regex- Pattern to match a recurring string
I want a pattern to match "+-+-+-+-+-.......",the "+-" can occur as many times,but they should be together...not like"+++--+---" 我希望模式匹配“ +-+-+-+-+ -.......”,“ +-”可以出现多次,但它们应该在一起...不像“ ++” +-+ ---“
I tried "[+-]+",but it doesn't specifies that + and - are consecutive 我尝试了“ [+-] +”,但没有指定+和-是连续的
The square brackets ( []
) specify a character class. 方括号( []
)指定字符类。 What you instead want is to use a non-capturing group: 相反,您想要使用的是非捕获组:
(?:\+-)+
You can of couse make it a capturing group (\\+-)+
if you want to well capture it all. 如果您想很好地捕获所有内容,可以将其设为捕获组(\\+-)+
。
Consider the following samples: 考虑以下示例:
+++--+---
-+-+-
-+-+-+
-+-+-+-
------
++++++
+-+-+-
+-+-+-+
+-+-+-+-
--++--++-
++--++--+
+-5
-+-A
Vallentin's pattern has no anchors and will match anything inside the string. Vallentin的模式没有锚点,它将匹配字符串中的任何内容。 (?:\\+-)+
Can the string end on the same character it starts with? 字符串可以以它开头的相同字符结尾吗?
if not, change it to: 如果不是,请将其更改为:
^(?:\\+-)+$
if it can: 如果可以:
For "+ only starts": Access full match result using pattern: ^(\\+(?:-|$))+$
对于“ +仅开始”:使用模式^(\\+(?:-|$))+$
访问完全匹配结果
For possibility of "+ and - starts": Access full match result using pattern: ^(?:([+-])(?!\\1))+$
对于“ +和-开始”的可能性:使用以下模式访问完全匹配结果: ^(?:([+-])(?!\\1))+$
Compare all three patterns @ this demo that defaults to Vallentin's pattern . 比较这三种默认为Vallentin模式的@ 模式 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.