【问题标题】:RegEx split string into words by space and containing charsRegEx 按空格将字符串拆分为单词并包含字符
【发布时间】:2018-02-13 21:08:43
【问题描述】:

如何使用Regex.Split(input, pattern) 方法执行这种拆分?

This is a [normal string ] made up of # different types # of characters

字符串数组输出:

1. This 
2. is
3. a
4. [normal string ]
5. made
6. up
7. of
8. # different types #
9. of
10. characters

它还应该保留前导空格,所以我想保留所有内容。一个字符串包含 20 个字符,字符串数组应包含所有元素的 20 个字符。

我尝试过的:

Regex.Split(text, @"(?<=[ ]|# #)")

Regex.Split(text, @"(?<=[ ])(?<=# #")

【问题讨论】:

  • 如果有未配对的特殊字符怎么办? “这个[字符串”应该如何拆分?
  • 我不知道这是否能解决您的问题,但您的两个示例的问题是,在第一个 [ ]|# # 中,只有 ]|# 上的 or 而第二个中的两个拆分彼此之后。 [ 也是一个特殊字符。您正在寻找像 (?&lt;=(\[ \])|(# #)) 这样的东西,尽管 (?&lt;=[\[#] [\]#]) 可能更好。

标签: c# regex


【解决方案1】:

我建议匹配,即提取单词,而不是拆分

string source = @"This is a [normal string ] made up of # different types # of characters";

// Three possibilities:
//   - plain word [A-Za-z]+
//   - # ... # quotation
//   - [ ... ] quotation  
string pattern = @"[A-Za-z]+|(#.*?#)|(\[.*?\])";

var words = Regex
  .Matches(source, pattern)
  .OfType<Match>()
  .Select(match => match.Value)
  .ToArray();

Console.WriteLine(string.Join(Environment.NewLine, words
  .Select((w, i) => $"{i + 1}. {w}")));

结果:

1. This
2. is
3. a
4. [normal string ]
5. made
6. up
7. of
8. # different types #
9. of
10. characters

【讨论】:

    【解决方案2】:

    你可以使用

    var res = Regex.Split(s, @"(\[[^][]*]|#[^#]*#)|\s+")
        .Where(x => !string.IsNullOrEmpty(x));
    

    regex demo

    (\[[^][]*]|#[^#]*#) 部分是一个捕获组,其值与拆分项一起输出到结果列表。

    模式详情

    • (\[[^][]*]|#[^#]*#) - 第 1 组:两种模式之一:
      • \[[^][]*] - [,后跟除 [] 之外的 0+ 个字符,然后是 ]
      • #[^#]*# - #,然后是除 # 之外的 0+ 个字符,然后是 #
    • | - 或
    • \s+ - 1+ 个空格

    C# demo:

    var s = "This is a [normal string ] made up of # different types # of characters";
    var results = Regex.Split(s, @"(\[[^][]*]|#[^#]*#)|\s+")
        .Where(x => !string.IsNullOrEmpty(x));
    Console.WriteLine(string.Join("\n", results));
    

    结果:

    This
    is
    a
    [normal string ]
    made
    up
    of
    # different types #
    of
    characters
    

    【讨论】:

      【解决方案3】:

      使用匹配方法会更容易,但是 it can be done 使用负前瞻:

      [ ](?![^\]\[]*\])(?![^#]*\#([^#]*\#{2})*[^#]*$)
      

      匹配后面没有的空格

      • [] 后跟] 之外的任何字符序列
      • # 后跟偶数个 #

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 2011-06-12
        • 2022-07-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多