简体   繁体   中英

C# split and get the value from inconsistent string

I have complication where i have to split a list of strings based on hex value in C# coding. Below are the list of the strings.

  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)

For example, if i get HEX value 20000, the correct corresponding value is no 14 which is 1/2FAST_16384 . Thus, i need to separate it into 3 different values which is a) 1/2 b) FAST and c) 16384 . Perhaps, someone can give some ideas on how to implement it, since the length and the pattern of the string is inconsistent. Not sure also if Regex can be used to tackle this problem.

You can use this regex:

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

Now you can split your input into groups:

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;

You can see a demo here

You could capture your values in 3 groups:

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

Explanation

^         # 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM