c# - 为定界符创建转义序列的严格方法

标签 c# regex string escaping delimiter

示例文本:(约翰,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.ReplaceRegex.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/

相关文章:

c# - 切换字符串的部分

c# - 未能从文本 'Windows.UI.Xaml.Controls.Primitives.PlacementMode' 创建 '鼠标'

c# - 单击选项卡控件的选定选项卡页眉时如何触发事件

C# 使用脚本创建数据库

javascript - 如何使用 jQuery 检查输入字符串中的大写字母

c++ - 如何为至少包含一个数字且不包含任何字母的字符串编写正则表达式?

c++ - 无法使用迭代器遍历字符串 : however my version with indices does work

java - 理解Java中的方法/类调用

c# - 使用 HTTPWebRequest 检查响应时间?

regex - 为什么我的 ack 正则表达式会得到额外的、意想不到的结果?