我想要一个正则表达式(尽可能高效,因为我使用 C++ 并且引擎效率不高)来匹配任何包含 % 且后面不立即跟随的字符串:
1) 一个字母 [a-zA-Z]
或
2) .NUMBERS[a-zA-Z]
或
3) 数字[a-zA-Z]
所以我想匹配这样的字符串:“dsfdf (%) dsfgs %d s32523”,“%d %d % %t dsg”
我不想匹配这样的字符串:“sfsf %d”,“dfsd %.464d,%353T”
最佳答案
使用negative look-ahead expression :
Negative lookahead is indispensable if you want to match something not followed by something else:
q(?!u)
meansq
not followed byu
就您而言q
是 %
,和u
是 ([.]?[0-9]+)?[a-zA-Z]
(可选点的可选前缀,后跟一个或多个数字以及字母后缀)。
注意:此表达式使用 +
在前瞻部分中,该功能没有得到普遍支持。如果您的正则表达式引擎不接受它,请通过替换 [0-9]+
设置人为限制,例如 20 位数字。与 [0-9]{1,20}
.
编辑:
What about writing my own parser?
如果您需要这个相对简单的正则表达式的终极速度,请使用手写解析器。这是一个简单的例子:
for (string str ; getline(cin, str) ; ) {
bool found = false;
size_t pos = 0;
while (!found && (pos = str.find('%', pos)) != string::npos) {
if (++pos == str.size()) {
found = true;
break;
}
if (str[pos] == '.') {
if (++pos == str.size()) {
found = true;
break;
}
if (!isdigit(str[pos])) {
found = true;
break;
}
}
while (isdigit(str[pos])) {
if (++pos == str.size()) {
found = true;
break;
}
}
found |= !isalpha(str[pos]);
}
cout << '"' << str << '"' << " : " << found << endl;
}
关于c++ - 正则表达式 - 匹配后面没有特定模式的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45033222/