Regex.Split的加号和减号 [英] Regex.Split on plus and minus sign
问题描述
我有一个字符串 1.5(+ 1.2 / -0.5)
。我想使用正则表达式以提取数值: {1.5,1.2,0.5}
。
我的计划是分裂与(
, + $ C $字符串C>,
/
和 -
当我与(
和 /
,它拆分OK,但如果我还添加了 +
和 -
,然后程序崩溃。
的String []富= Regex.Split(1.5(+ 1.5 / -0.5),@));
// OK
的String []富= Regex.Split((= [(/?)1.5(+ 1.5 / - 0.5),@ - ))(= [(/ +?)];
//异常逮住
和捕捉到的异常是:
System.ArgumentException:解析(= [(/ + - ) ]) - [XY]范围内
相反的顺序
块引用>
解决方案破折号当方括号在正则表达式里面这意味着一系列特殊字符:
[AZ]
指从A
到以Z
当你写[(/ + - )]
,它实际上意味着(
,或+
到)
。这个错误来自于一个事实,即在ASCII顺序)
到来之前+
,所以一个字符范围[+ - )]
无效
要解决这个问题,破折号必须总是第一个或最后时在括号中,或者它需要是反斜杠。
和我同意,我可能会使用一个全局RegExp挑出
[0-9] +
,而不是分裂,以削减一切。I have a string
1.5(+1.2/-0.5)
. I want to use Regex to extract numerical value:{1.5, 1.2, 0.5}
.My plan is to split the string with
(
,+
,/
and-
. When I do split with(
and/
, it splits OK, but if I also add+
and-
, then program crashes.string[] foo = Regex.Split("1.5(+1.5/-0.5)", @"(?=[(/)])"); // OK string[] foo = Regex.Split("1.5(+1.5/-0.5)", @"(?=[(/+-)])"); // Exception catched
And the caught exception is:
System.ArgumentException: parsing "(?=[(/+-)])" - [x-y] range in reverse order
解决方案The dash is a special character when inside square brackets in a regexp. It means a range:
[a-z]
means any character froma
toz
. When you wrote[(/+-)]
, it would actually mean(
, or any character from+
to)
. The error comes from the fact that in ASCII ordering)
comes before+
, so a character range[+-)]
is invalid.To fix this, dash must always come first or last when in brackets, or it needs to be backslashed.
And I agree, I'd probably use a global regexp to pick out
[0-9.]+
, and not a split to cut on everything else.这篇关于Regex.Split的加号和减号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!