示例文本:(约翰,36 岁,阿拉巴马州)
我在我的代码中所做的是首先匹配圆括号 (),然后使用逗号作为分隔符拆分其中的内容。
private static IEnumerable<string> GetValues(string value)
{
var matches = Regex.Matches(value, @"\(.*\)");
if (matches.Count == 0) return new string[0];
var valueSplit = matches[0].Value;
var theString = valueSplit.Trim('(', ')');
var wordSplit = theString.Split(',').Select(x=>x.Trim());
return wordSplit;
}
对于示例文本(约翰,36 岁,阿拉巴马州),上面的代码返回:
- 约翰
- 36
- 阿拉巴马州
现在的问题是我应该如何为我用作分隔符的逗号创建转义序列。
这样对于示例文本(John 36, Alton,<-something before this comma Alabama)返回
- 约翰
- 36
- 阿拉巴马州奥尔顿
并且递归地允许我什至转义转义序列本身?我尝试了 String.Replace 和 Regex.Replace 但无济于事。
这是一个 Fiddle
最佳答案
如果你只想要 3 个子字符串,那么你可以从 Split 中限制它
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
foreach (var item in GetValues("(John, 36, Alabama, Whatever, Manager)"))
{
Console.WriteLine(item);
}
}
private static IEnumerable<string> GetValues(string value)
{
var matches = Regex.Matches(value, @"\(.*\)");
if (matches.Count == 0) return new string[0];
var valueSplit = matches[0].Value;
var theString = valueSplit.Trim('(', ')');
var wordSplit = theString.Split(new char[]{','}, 3, StringSplitOptions.None).Select(x=>x.Trim());
return wordSplit;
}
}
输出:
- 约翰
- 36
- 阿拉巴马州,随便什么,经理
这是 Fiddle
关于c# - 为定界符创建转义序列的严格方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30204327/