【发布时间】:2013-10-01 20:11:46
【问题描述】:
我正在寻找一个正则表达式来仅匹配 C++ 项目中的 MBCS 字符串。这些是包含在双引号中的字符串,没有L"..." 或_T("...") 说明符。任何代码行都可以有多个引号。字符串可以包含不应结束匹配的转义子字符串。以下是几个例子:
"This is a MBCS string"; // "This is a MBCS string" match
_T("This is maybe a unicode string"); // no match
L"This is a unicode string"; // no match
"These both" + "should match"; // "These both" and "should match" match
"This is a \"quoted\" string"; // "This is a \"quoted\" string" match
我有一个正则表达式,可以使用负回溯(?<!#include )(?<!_T\()(?<!\\)(?<!L)\"(.*?)\"(?<!\\\") 处理所有这些问题,但它变得更加复杂。它开始在一行上混合字符串类型出现问题。
_T("Maybe this") + "is a match"; // "is this" match but instead would match ") + "
do_something(_T("This doesn't match")) + do_something("but this does match"); // "but this does match" match but instead it matches ")) + do_something("
我怎样才能让正则表达式在 _T("") 和 L"" 单词上不匹配,但仍然匹配它们以吃掉结尾引号而不将其作为匹配项返回?
编辑:这个正则表达式 (?:_T\(\"[^\"]+\"\).*?|L\"[^\"]+\".*?)*(?<!#include )(?<!_T\()(?<!L)(?<!\\)\"(.*?)\"(?<!\\\") 几乎可以完成这项工作,但还有一个测试用例失败了,我最初没想过要包括在内。
_T("don't match this") + _T("or this"); // shouldn't match anything, matches ") + _T("
【问题讨论】:
-
你不能全部匹配然后过滤掉那些以
L或_T(开头的吗? -
如果您的字符串格式正确,我会提取每个
(?:L|_T\s*\(\s*)?"(?:[^\"]+|\\")*"字符串,然后检查它是否在开始引号之前有前缀。 -
是的,这绝对是一个想法。我想知道是否有一种简单的方法来提出正确的正则表达式,但是当我通过一些真实文件运行它时,这看起来越来越难了。