正则表达式扫描带符号的固定长度小数

时间:2021-12-14 01:52:19

How to write a regular expression to scan whether input is a signed decimal or not?

如何编写正则表达式来扫描输入是否为带符号的小数?

e.g:

例如:

-1.234567
-.1234567
123456789
1.2345678
1234567.8
-1234.567

Input length must be 9.

输入长度必须为9。

2 个解决方案

#1


2  

Why are you using RegEx? There are better methods to determine if a string is signed or not.

你为什么使用RegEx?有更好的方法来确定字符串是否已签名。

Use decimal.TryParse() and Math.Sign() to get your answer.

使用decimal.TryParse()和Math.Sign()来获得答案。

string input = "-1.2342";

decimal decValue;
bool isDecimal = decimal.TryParse(input, out decValue);

if (isDecimal)
{
    int signValue = Math.Sign(decValue);
}
else
{
    throw new Exception("Not a valid decimal!");
}

#2


0  

You could do it the hard way:

你可以这么做:

([-\d]\d\.\d\d\d\d\d\d|[-\d]\d\d\.\d\d\d\d\d|[-\d]\d\d.\d\d\d\d|...)

Basically this is any of the forms you listed OR-ed. This is quite tedious, but right now I can't think of any other way that will work for all possible inputs.

基本上这是您列出的任何形式的OR-ed。这是相当繁琐的,但是现在我想不出任何其他适用于所有可能输入的方式。

#1


2  

Why are you using RegEx? There are better methods to determine if a string is signed or not.

你为什么使用RegEx?有更好的方法来确定字符串是否已签名。

Use decimal.TryParse() and Math.Sign() to get your answer.

使用decimal.TryParse()和Math.Sign()来获得答案。

string input = "-1.2342";

decimal decValue;
bool isDecimal = decimal.TryParse(input, out decValue);

if (isDecimal)
{
    int signValue = Math.Sign(decValue);
}
else
{
    throw new Exception("Not a valid decimal!");
}

#2


0  

You could do it the hard way:

你可以这么做:

([-\d]\d\.\d\d\d\d\d\d|[-\d]\d\d\.\d\d\d\d\d|[-\d]\d\d.\d\d\d\d|...)

Basically this is any of the forms you listed OR-ed. This is quite tedious, but right now I can't think of any other way that will work for all possible inputs.

基本上这是您列出的任何形式的OR-ed。这是相当繁琐的,但是现在我想不出任何其他适用于所有可能输入的方式。