[英]C# split and get the value from inconsistent string
我有一个复杂的问题,我必须根据 C# 编码中的十六进制值拆分字符串列表。 下面是字符串列表。
例如,如果我得到 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.