正则表达式模式选择BETWEEN匹配引号的数据
假设我有以下字符串,我想在其上运行正则表达式:
This is a test string with "quotation-marks" within it. The "problem" I am having, per-se, is "knowing" which "quotation-marks" go with which words.
现在,假设我想用引号替换引号之间的所有字符,例如空格。 我以为我可以使用正则表达式进行如下操作:
Find What: (\"[^"]*?)(\-)([^"]*?\") Replace With: $1 $3
我遇到的问题是使用这种模式,它没有考虑引号是打开还是关闭语句。
因此,在上面的示例中, per-se
的-
字符将被替换为空格,因为它在2个引号之间,但在结束标记和开始标记之间 – 当我特别想在文本中查看开头和结束标记 。
你如何在这样的正则表达式中解释这一点?
我希望这是有道理的。
我正在使用VB / C#Regex。
只是为了完成这个问题(并希望在必要时再详细说明),我想得到的最终结果是:
This is a test string with "quotation marks" within it. The "problem" I am having, per-se, is "knowing" which "quotation marks" go with which words.
谢谢!!
您遇到的问题与尝试匹配HTML或打开和关闭括号的人相同,正则表达式只能匹配常规语言,并且知道哪个"
是关闭的,而且开放的是除了微不足道的情况之外的任何东西。”
编辑:正如Vasili Syrakis的回答所示,有时它可以完成,但正则表达式是解决此类问题的脆弱解决方案。
话虽如此,你可以在简单的情况下转换你的问题。 由于您使用的是.NET,因此您可以简单地匹配每个带引号的字符串并使用带有匹配评估程序的重载 。
Regex.Replace(text, "\".*?\"", m => m.Value.Replace("-", " "))
测试:
var text = @"This is a test string with ""quotation-marks"" within it. The ""problem"" I am having, per-se, is ""knowing"" which ""quotation-marks"" go with which words."; Console.Write(Regex.Replace(text, "\".*?\"", m => m.Value.Replace("-", " "))); //This is a test string with "quotation marks" within it. //The "problem" I am having, per-se, is "knowing" which "quotation marks" //go with which words.
从长远来看,执行此操作的常规方法可能更容易维护,而不是正则表达式:
public static String replaceDashInQuotes(this string source, String newValue) { StringBuilder sb = new StringBuilder(); bool inquote = false; for (int i = 0; i < source.Length; i++) { if (source[i] == '\"') inquote = !inquote; if (source[i] == '-' && inquote) sb.Append(newValue); else sb.Append(source[i]); } return sb.ToString(); }
然后使用它:
var s = @"This is a test string with ""quotation-marks"" within it. The ""problem"" I am having, per-se, is ""knowing"" which ""quotation-marks"" go with which words."; MessageBox.Show(s.replaceDashInQuotes(" "));
我将字符串拆分为一个字符串数组,使用引号“作为分隔符。然后所有具有奇数索引的字符串将是一对引号内的字符串,仅在aSplittedString [oddIndex]上使用你的正则表达式,然后用“连接整个数组。
你需要做的是明确地仅匹配具有 -
引号内的字符串。
用这个:
(\"[^"]*.*?)-(.*?\")
工作示例: http : //regex101.com/r/jK5eL9
这里唯一的问题是它只适用于引号中的单个word-word
实例。 如果你有"word-word, and word-word"
它就会失败。