我需要标记一个字符串,这样标记可以是:
- 双引号内
- 空格分隔
带引号的字符串必须处理转义:this: "is included in\"single token\""
应该变成这样:
[this:] [is included in "single token"]
或者这个:
[this:] [is included in \"single token\"]
( token 是@"[^\s]"
,不是@"\w"
)
我见过很多部分问题的解决方案:
- 找到所有带引号的字符串 - 但会留下所有未带引号的标记
- 找到所有不带引号的标记——遗漏带引号的字符串
不幸的是,我找不到将这两个问题的解决方案融合在一起的方法...
这是我目前所拥有的:
static void Main(string[] args) {
var inputs = new List<string>
{
@"bef\`ore`xy z`after",
@"start `with simple` expression: `i am xprsion` and this is empty: `` ...",
@"now `with some tabs` expression",
@"nothing \but\ escapers\\\",
@"some #@ other kind$ of whildcards...",
@"and now `with \`allegedly\` escape` char",
@"tight` or even `connected",
}.Select(s => s.Replace('`', '"'));
var sections = new[]
{
@"(?<i>[^\s]+)",
@"((?<!\\)`(?<i>.*?)(?<!\\)`)", // quoted
};
var pattern = string.Join("|", sections).Replace("`","\"");
foreach (var i in inputs)
{
Regex.Matches(i, pattern)
.Cast<Match>()
.Select(m => m.Groups["i"].Value)
.ToList()
.ForEach(s => Console.Write("[{0}]", s));
Console.WriteLine();
}
Console.ReadKey();
}
但是引用模式和空白分隔模式的结合破坏了这一切......
最佳答案
您可以使用此正则表达式进行匹配
(?<=[^\\]|^)".*?(?<=[^\\])"|(\\"|[\w])+
不要忘记使用 ""
转义 "
并使用逐字字符串 @
Regex.Matches(input,yourRegex)
.Cast<Match>()
.Select(x=>x.Value)
.ToList();
Demo {你不能在此处更改输入,打开该站点的新实例}
关于c# - 如何标记空格和引号字符串,处理转义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17388671/