簡體   English   中英

C# 拆分並從不一致的字符串中獲取值

[英]C# split and get the value from inconsistent string

我有一個復雜的問題,我必須根據 C# 編碼中的十六進制值拆分字符串列表。 下面是字符串列表。

  1. 1/2JHT(0x2)
  2. 3/4JHT(0x4)
  3. 7/8JHT(0x8)
  4. 1/2JHT-B(0x10)
  5. 3/4JHT-B(0x20)
  6. (126;112)RS(0x80)
  7. (194;178)RS(0x100)
  8. (208;192)RS(0x200)
  9. 2/3RET(0x1000)
  10. 3/4RET(0x2000)
  11. 7/8RET(0x4000)
  12. 1/2FAST_1024(0x8000)
  13. 1/2FAST_4096(0x10000)
  14. 1/2FAST_16384(0x20000)

例如,如果我得到 HEX 值 20000,則正確的對應值是 no 14 ,即1/2FAST_16384 因此,我需要將它分成 3 個不同的值,即 a) 1/2 b) FAST和 c) 16384 也許有人可以就如何實現它給出一些想法,因為字符串的長度和模式不一致。 也不確定是否可以使用 Regex 來解決這個問題。

您可以使用此正則表達式:

(?<a>(\(\d+;\d+\))|(\d+\/\d+))(?<b>[^\(_]+)(_(?<c>[^\(]+))?

現在您可以將輸入分成幾組:

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;

你可以在這里看到一個演示

您可以將您的價值觀分為 3 組:

^(\\(?\\d+[/;]\\d+\\)?)([AZ-]+)(?:_(\\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

輸出 C# 演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM