[英]C# regex split for A non-zero digit followed by an arbitrary number of zero
I have a number as a string "10009003" i would like to split it using regex to always get the first non-zero digit and include all trailing zeroes. 我有一个数字作为字符串“ 10009003”,我想使用正则表达式将其拆分,以始终获取第一个非零数字并包括所有尾随零。 Then get the next non-zero number followed by its trailing zeroes.
然后获取下一个非零数字,其后跟零。 If a non-zero number has no trailing zeroes just grab it.
如果非零数字没有尾随零,则抓住它。
The above number string should result in array/list of length/count 3 as follows [0] = 1000, [1] = 900, [2] =3 上面的数字字符串应导致长度为3的数组/列表,如下所示:[0] = 1000,[1] = 900,[2] = 3
I have tried this code; 我已经试过了这段代码;
var someNumberString = "10009003";
string s = @"[^1-9]+";
string[] strArray = Regex.Split(someNumberString, s);
which only output the following but the zeros are missing; 仅输出以下内容,但不包含零; [0] = 1 , [1] = 9 , [2] = 3
[0] = 1,[1] = 9,[2] = 3
How do i get the regex to include the trailing zeros? 我如何使正则表达式包含尾随零?
Thanks in advance for the help:) 先谢谢您的帮助:)
You can use this lookbehind and lookahead based regex: 您可以使用基于lookbehind和lookahead的正则表达式:
var someNumberString = "10009003";
string s = @"(?<=[1-9]0*)(?=[1-9])";
string[] strArray = Regex.Split(someNumberString, s);
Console.Write(string.Join(" ", strArray));
//=> 1000 900 3
(?<=[1-9]0*)
( Lookbehind ) - if current position preceded by a non-zero digit and 0 or more zeroes (?<=[1-9]0*)
( 向后看 )-如果当前位置前面有一个非零数字和0个或多个零 (?=[1-9])
( Lookahead ) - if current position is followed by a non-zero digit (?=[1-9])
( 前瞻 )-如果当前位置后跟一个非零数字 You could use regex.Matches
function like below. 您可以使用
regex.Matches
函数,如下所示。
String input = @"10009003";
Regex rgx = new Regex(@"[1-9]+0*");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[0].Value);
[1-9]
matches the digit which ranges from 1 to 9. 0*
matches zero or more 0
's. [1-9]
匹配范围从1到9的数字0*
匹配零个或多个0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.