C# 用于在单引号或双引号内不拆分字符串的正则表达式
我有一个正则表达式,在C中具有以下模式# 基本上,它用于命令行解析 如果我传递下面的cmd行args,它也会溢出C# 用于在单引号或双引号内不拆分字符串的正则表达式,c#,.net,regex,C#,.net,Regex,我有一个正则表达式,在C中具有以下模式# 基本上,它用于命令行解析 如果我传递下面的cmd行args,它也会溢出C: /Data:SomeData /File:"C:\Somelocation" 如何使其不适用于双引号或单引号内的字符?您可以通过两个步骤完成此操作: 使用第一个正则表达式 Regex args = new Regex("[/-](?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); 将字符串拆分为不同的参数。然后使用正则表达式 Regex param = ne
C:
/Data:SomeData /File:"C:\Somelocation"
如何使其不适用于双引号或单引号内的字符?您可以通过两个步骤完成此操作: 使用第一个正则表达式
Regex args = new Regex("[/-](?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
将字符串拆分为不同的参数。然后使用正则表达式
Regex param = new Regex("[=:](?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
将每个参数拆分为参数/值对
说明:
[=:] # Split on this regex...
(?= # ...only if the following matches afterwards:
(?: # The following group...
[^"]*" # any number of non-quote character, then one quote
[^"]*" # repeat, to ensure even number of quotes
)* # ...repeated any number of times, including zero,
[^"]* # followed by any number of non-quotes
$ # until the end of the string.
) # End of lookahead.
基本上,如果前面有偶数个引号,它会在字符串中向前看。如果有,我们就在一条线之外。然而,这个(有些可管理的)正则表达式只处理双引号,并且只有在双引号中没有转义引号时才处理
以下正则表达式正确处理单引号和双引号,包括转义引号。但我想你会同意,如果有人在生产代码中发现了这一点,我保证会在以下方面发表一篇专题文章:
进一步解释这个怪物。你应该阅读“”来理解为什么你的问题没有通用的解决方案。正则表达式无法将其处理到任意深度。一旦您开始转义转义角色或转义转义角色或。。。你迷路了。您的用例需要一个解析器而不是正则表达式。/code>/Data:'“'将破坏您的正则表达式。这是一个很好的答案,并且符合所提出的问题,但这并不是在生产级别上应该使用正则表达式来完成的任务。如果OP担心边缘情况,他应该写一个真正的lexer。@FrankieTheKneeMan:你说得对;我无法在这个正则表达式中处理单引号。新的正则表达式怎么样?希望它不会让你做噩梦:)天哪,这是一个很好的正则表达式。@FrankieTheKneeMan:是的,我想我得了严重的倾斜牙签综合症。它无法处理App.exe/Input:“C:\path”。我希望参数=Input,值=C:\Path
[=:] # Split on this regex...
(?= # ...only if the following matches afterwards:
(?: # The following group...
[^"]*" # any number of non-quote character, then one quote
[^"]*" # repeat, to ensure even number of quotes
)* # ...repeated any number of times, including zero,
[^"]* # followed by any number of non-quotes
$ # until the end of the string.
) # End of lookahead.
Regex param = new Regex(
@"[=:]
(?= # Assert even number of (relevant) single quotes, looking ahead:
(?:
(?:\\.|""(?:\\.|[^""\\])*""|[^\\'""])*
'
(?:\\.|""(?:\\.|[^""'\\])*""|[^\\'])*
'
)*
(?:\\.|""(?:\\.|[^""\\])*""|[^\\'])*
$
)
(?= # Assert even number of (relevant) double quotes, looking ahead:
(?:
(?:\\.|'(?:\\.|[^'\\])*'|[^\\'""])*
""
(?:\\.|'(?:\\.|[^'""\\])*'|[^\\""])*
""
)*
(?:\\.|'(?:\\.|[^'\\])*'|[^\\""])*
$
)",
RegexOptions.IgnorePatternWhitespace);