重复特定的正则表达式模式 [英] Repeating specific regex pattern
问题描述
我有一个正则表达式模式:
I have a regex pattern:
boost::regex regex = "@ABC-\\d+"
表示模式以@ ABC-开头,后跟一个或多个数字.
我希望此模式能够与该模式匹配一次或多次,即:
which means pattern starting with @ABC- and followed by one or more digits.
I want this pattern to be able to match this pattern one or more times that is:
boost::regex regex = "@ABC-\\d+@ABC-\\d+@ABC-\\d+@ABC-\\d+etc, etc"
推荐答案
使用 分组构造 ,并应用 量化器 ,然后使用 ^
和 $
锚点 ,以确保整个字符串与模式匹配:
Use a grouping construct and apply a quantifier to it, and use ^
and $
anchors to make sure the whole string is matched against the pattern:
示例:
R"(^(@ABC-\d+)+$)"
或-使用非捕获组,它永远不会创建一个在内存缓冲区内捕获(此分组构造旨在仅对子模式进行分组以匹配字符串序列):
or - with a non-capturing group that will never create a capture inside the memory buffer (this grouping construct is meant to only group subpatterns to match string sequences):
R"(^(?:@ABC-\d+)+$)"
^^
如果字符串可以为空,则用 *
替换最后一个 +
: R(^(@(ABC- \ d +)* $)"
.
If the string can be empty, replace the last +
with *
: R"(^(@ABC-\d+)*$)"
.
请注意,在C ++中,声明正则表达式模式时应首选使用原始字符串文字,以避免过多的反斜杠.
Note that in C++, raw string literals are preferred when declaring regular expression patterns to avoid excessive backslashes.
这篇关于重复特定的正则表达式模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!