简体   繁体   English

正则表达式为十进制值和可选字符串

[英]Regex for decimal value and optional string

I'm looking for a Regex to validate a rating (1-10) + optional text. 我正在寻找一个正则表达式来验证评级(1-10)+可选文本。 Rating is a decimal, with 1 point, which can use both dot or comma separator. 等级是小数,有1个点,可以使用点或逗号分隔符。 Followed by an optional space + string. 后跟可选的空格+字符串。

Valid 有效

  • 7 7
  • 7,5 7,5
  • 7.5 7.5
  • 7,5 This is my string 7,5这是我的字符串
  • 7.5 Hello 7.5你好

Invalid 无效

  • 7,75 7,75
  • 11 11
  • 7This is my string 7这是我的字符串
  • 7.This is my string 这是我的字符串
  • 10.5 string 10.5字符串

I've got this for getting the decimal values, but I'm not sure how to get the optional text behind it. 我得到了这个来获取小数值,但我不知道如何获得它背后的可选文本。

^(10|\d)([\.\,]\d{1,1})?$

Judging by your examples, the space after the initial number is not optional. 根据您的示例判断,初始数字后面的空格不是可选的。 Thus, the pattern you may use is 因此,您可以使用的模式是

^(?:10|[1-9](?:[.,][0-9])?)(?:\s.*)?$

or - since a partial match with Regex.IsMatch is enough to validate the string - replace (?:\\s.*)?$ with a negative lookahead (?!\\S) that will require a whitespace or end of string after the number: 或者 - 因为与Regex.IsMatch的部分匹配足以验证字符串 - 用负前瞻(?!\\S)替换(?:\\s.*)?$ ,这将需要在数字后面的空格或字符串结尾:

^(?:10|[1-9](?:[.,][0-9])?)(?!\S)
                           ^^^^^^^

See the regex demo 请参阅正则表达式演示

Details : 细节

  • ^ - start of a string ^ - 字符串的开头
  • (?:10|[1-9](?:[.,][0-9])?) - either 10 or a digit from 1 to 9 followed with an optional sequence of a , or . (?:10|[1-9](?:[.,][0-9])?) - 1019的数字,然后是a的可选序列,. and any single digit and then... 和任何一个数字,然后......
  • (?:\\s.*)?$ - an optional sequence of any whitespace followed with any chars up to the end of string - OR - (?:\\s.*)?$ - 任意空格的可选序列,后跟任何字符串直到字符串的结尾 - 或者 -
  • (?!\\S) - a negative lookahead that fails the match if there is no non-whitespace char immediately to the right of the current position. (?!\\S) - 如果当前位置右侧没有非空格字符,则会导致匹配失败的否定前瞻。

C# test : C#测试

var strs = new List<string> { "7","7,5","7.5","7,5 This is my string","7.5 Hello","7,75","11","7This is my string","7.This is my string","10.5 string"};
var pattern = @"^(?:10|[1-9](?:[.,][0-9])?)(?:\s.*)?$";
foreach (var s in strs)
    if (Regex.IsMatch(s, pattern))
        Console.WriteLine("{0} is correct.", s);
    else
        Console.WriteLine("{0} is invalid.", s);

Output: 输出:

7 is correct.
7,5 is correct.
7.5 is correct.
7,5 This is my string is correct.
7.5 Hello is correct.
7,75 is invalid.
11 is invalid.
7This is my string is invalid.
7.This is my string is invalid.
10.5 string is invalid.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM