我需要2个正则表达式,它可以在.NET来检测用户是否在一小部分类型:
只有分数值没有任何整部分(不想检查1 1/4,3 1/2等) ONLY:1/2,3/4,8/3等。分子分母可以是浮点数或整数。
ALL有效馏分,例如1/3,2/3,1 1/4等
感谢。
我需要2个正则表达式,它可以在.NET来检测用户是否在一小部分类型:
只有分数值没有任何整部分(不想检查1 1/4,3 1/2等) ONLY:1/2,3/4,8/3等。分子分母可以是浮点数或整数。
ALL有效馏分,例如1/3,2/3,1 1/4等
感谢。
对于第一
对于在##/##
,其中分子或分母可以是任何长度形式的任何部分,你可以只使用:
\d+(\.\d+)?/\d+(\.\d+)?
抓住尽可能多的数字作为您可以立即在字面斜杠前后,只要至少有一个或多个这些数字。如果有一个小数点,它也必须跟着一个或多个数字,但整个组是可选的,只能出现一次。
对于第二
假设它必须是一小部分,因此整体人数就喜欢1
起不到作用,只要坚持正面
\d*\s*
抓住以下一些数字并在其余部分之前留出空白。
试试这个:
/// <summary>
/// A regular expression to match fractional expression such as '1 2/3'.
/// It's up to the user to validate that the expression makes sense. In this context, the fractional portion
/// must be less than 1 (e.g., '2 3/2' does not make sense), and the denominator must be non-zero.
/// </summary>
static Regex FractionalNumberPattern = new Regex(@"
^ # anchor the start of the match at the beginning of the string, then...
(?<integer>-?\d+) # match the integer portion of the expression, an optionally signed integer, then...
\s+ # match one or more whitespace characters, then...
(?<numerator>\d+) # match the numerator, an unsigned decimal integer
# consisting of one or more decimal digits), then...
/ # match the solidus (fraction separator, vinculum) that separates numerator from denominator
(?<denominator>\d+) # match the denominator, an unsigned decimal integer
# consisting of one or more decimal digits), then...
$ # anchor the end of the match at the end of the string
", RegexOptions.IgnorePatternWhitespace
);
/// <summary>
/// A regular expression to match a fraction (rational number) in its usual format.
/// The user is responsible for checking that the fraction makes sense in the context
/// (e.g., 12/0 is perfectly legal, but has an undefined value)
/// </summary>
static Regex RationalNumberPattern = new Regex(@"
^ # anchor the start of the match at the beginning of the string, then...
(?<numerator>-?\d+) # match the numerator, an optionally signed decimal integer
# consisting of an optional minus sign, followed by one or more decimal digits), then...
/ # match the solidus (fraction separator, vinculum) that separates numerator from denominator
(?<denominator>-?\d+) # match the denominator, an optionally signed decimal integer
# consisting of an optional minus sign, followed by one or more decimal digits), then...
$ # anchor the end of the match at the end of the string
" , RegexOptions.IgnorePatternWhitespace);
#1。 \ d/{1} \ d(我不知道怎么做#2) – ActiveX 2012-07-30 15:57:24
请记住,只有'\ d'只匹配一个数字。要匹配0或更多,可以使用'\ d *'。要再匹配1个,请使用'\ d +'。在同样的逻辑中,在'/'之后不需要'{1}',因为它意味着你的意思是“一个字面斜杠” – 2012-07-30 16:05:05