使用多个条件标记字符串

时间:2021-06-03 21:44:05

标签: c# regex

对于下面的字符串:

var str = "value0 'value 1/5' 'x ' value2";

有没有办法解析那个字符串,这样我就可以得到

arr[0] = "value0";
arr[1] = "value 1/5";
arr[2] = "x ";
arr[3] = "value2";

可能带有单引号的值的顺序是任意的。大小写无关紧要。

我可以使用像这样的正则表达式来获取单引号之间的所有值

"'(.*?)'"

但我需要这些值相对于其他非单引号值的顺序。

2 个答案:

答案 0 :(得分:2)

使用

'(?<val>.*?)'|(?<val>\S+)

regex proof

说明

--------------------------------------------------------------------------------
  '                        '\''
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    .*?                      any character except \n (0 or more times
                             (matching the least amount possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  '                        '\''
--------------------------------------------------------------------------------
 |                        OR
--------------------------------------------------------------------------------
  (                        group and capture to \2:
--------------------------------------------------------------------------------
    \S+                      non-whitespace (all but \n, \r, \t, \f,
                             and " ") (1 or more times (matching the
                             most amount possible))
--------------------------------------------------------------------------------
  )                        end of \2

C# code

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"'(?<val>.*?)'|(?<val>\S+)";
        string input = @"value0 'value 1/5' 'x ' value2";
        
        foreach (Match m in Regex.Matches(input, pattern))
        {
            Console.WriteLine(m.Groups["val"].Value);
        }
    }
}

答案 1 :(得分:1)

在 C# 中,您可以重用同一个命名的捕获组,因此您可以使用替代 def convert (fahr): cels = fahr *1.8 + 32 return cels convert(10) # runs without error 对两个部分使用相同的组名。

|

模式匹配:

  • '(?<val>[^']+)'|(?<val>\S+) 匹配单引号
  • ' 在组 val 中捕获匹配除 (?<val>[^']+) 之外的任何字符的 1 倍以上以不匹配空字符串
  • ' 匹配单引号
  • '
  • | 在组 val 中捕获匹配任何非空白字符的 1 倍以上

查看 .NET regex demoC# demo

enter image description here

例如

(?<val>\S+)

输出

string pattern = @"'(?<val>[^']+)'|(?<val>\S+)";
var str = "value0 'value 1/5' 'x ' value2";
foreach (Match m in Regex.Matches(str, pattern))
{
    Console.WriteLine(m.Groups["val"].Value);
}
相关问题