我在下面得到了这个适用于单引号的代码.它找到单引号之间的所有单词.但是我如何修改正则表达式以使用双引号?
关键字来自表单帖子
所以
keywords = 'peace "this world" would be "and then" some'
// Match all quoted fields
MatchCollection col = Regex.Matches(keywords, @"'(.*?)'");
// Copy groups to a string[] array
string[] fields = new string[col.Count];
for (int i = 0; i < fields.Length; i++)
{
fields[i] = col[i].Groups[1].Value; // (Index 1 is the first group)
}// Match all quoted fields
MatchCollection col = Regex.Matches(keywords, @"'(.*?)'");
// Copy groups to a string[] array
string[] fields = new string[col.Count];
for (int i = 0; i < fields.Length; i++)
{
fields[i] = col[i].Groups[1].Value; // (Index 1 is the first group)
}
Run Code Online (Sandbox Code Playgroud)
Joe*_*ton 17
您只需替换'
with \"
并删除文字即可正确重建.
MatchCollection col = Regex.Matches(keywords, "\\\"(.*?)\\\"");
Run Code Online (Sandbox Code Playgroud)
Jos*_*nig 10
完全相同,但用双引号代替单引号.双引号在正则表达式模式中并不特殊.但我通常会添加一些内容以确保我不会在单个匹配中跨越多个引用的字符串,并且可以容纳双重双引号转义:
string pattern = @"""([^""]|"""")*""";
// or (same thing):
string pattern = "\"(^\"|\"\")*\"";
Run Code Online (Sandbox Code Playgroud)
这转换为文字字符串
"(^"|"")*"
Run Code Online (Sandbox Code Playgroud)
使用这个正则表达式:
"(.*?)"
Run Code Online (Sandbox Code Playgroud)
或者
"([^"]*)"
Run Code Online (Sandbox Code Playgroud)
在 C# 中:
var pattern = "\"(.*?)\"";
Run Code Online (Sandbox Code Playgroud)
或者
var pattern = "\"([^\"]*)\"";
Run Code Online (Sandbox Code Playgroud)
你想匹配"
还是'
?
在这种情况下你可能想做这样的事情:
[Test]
public void Test()
{
string input = "peace \"this world\" would be 'and then' some";
MatchCollection matches = Regex.Matches(input, @"(?<=([\'\""])).*?(?=\1)");
Assert.AreEqual("this world", matches[0].Value);
Assert.AreEqual("and then", matches[1].Value);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
47553 次 |
最近记录: |