C#split并从不一致的字符串中获取值

时间:2018-02-07 04:01:50

标签: c# regex

我有一个复杂的问题,我必须在C#编码中根据十六进制值分割一个字符串列表。以下是字符串列表。

  1. 1 / 2JHT(0X2)
  2. 3 / 4JHT(为0x4)
  3. 7 / 8JHT(0x8中)
  4. 1 / 2JHT-B(0×10)
  5. 3 / 4JHT-B(0×20)
  6. (126; 112)RS(0x80的)
  7. (194; 178)RS(0x100的)
  8. (208; 192)RS(在0x200)
  9. 2 / 3RET(0×1000)
  10. 3 / 4RET(为0x2000)
  11. 7 / 8RET(0x4000的)
  12. 1 / 2FAST_1024(0x8000)时
  13. 1 / 2FAST_4096(0x10000的)
  14. 1 / 2FAST_16384(地址0x20000)
  15. 例如,如果我得到HEX值20000,则正确的对应值为 14 1 / 2FAST_16384 。因此,我需要将其分成3个不同的值,即a) 1/2 b) FAST 和c) 16384 。也许,有人可以就如何实现它提出一些想法,因为字符串的长度和模式是不一致的。还不确定是否可以使用Regex来解决这个问题。

2 个答案:

答案 0 :(得分:0)

您可以使用此正则表达式:

var regex = new Regex("(?<a>(\\(\\d+;\\d+\\))|(\\d+\\/\\d+))(?<b>[^\\(_]+)(_(?<c>[^\\(]+))?");

var input = "1/2FAST_1024(0x8000)";
var match = regex.Match(input);
var a = match.Groups["a"].Value; // a is "1/2";
var b = match.Groups["b"].Value; // b is "FAST";
var c = match.Groups["c"].Success // c is optional
    ? match.Groups["c"].Value // in this case it will be "1024"
    : string.Empty;

现在您可以将输入分组:

{{1}}

您可以看到演示here

答案 1 :(得分:0)

您可以在3组中捕获您的值:

^(\(?\d+[/;]\d+\)?)([A-Z-]+)(?:_(\d+))?

<强>解释

^         # Assert position at the beginning of the string.
(         # Capture in a group (group 1)
 \(?      # Match optional opening parenthesis
 \d+      # match one or more digits
 [/;]     # Match forward slash or semicolon
 \d+      # Match One or more digits
 \)?      # Match optional closing parenthesis
)         # Close captured group 
(         # Capture in a group (group 2)
 [A-Z-]+  # Match an uppercase character or a hyphen one or more times
)         # Close captured group 
(?:       # A non capturing group
 _        # Match an underscore
 (\d+)    # Capture one or more digits in a group (group 3)
)?        # Close non capturing group and make it optional

Output C# demo