如何在Regex C#中匹配字符串格式

时间:2018-09-13 12:10:54

标签: c# regex string

我传递了正确的字符串formate,但是它没有返回true。

string dimensionsString= "13.5 inches high x 11.42 inches wide x 16.26 inches deep";
 // or 10.1 x 12.5 x 30.9 inches
 // or 10.1 x 12.5 x 30.9 inches ; 3.2 pounds

Regex rgxFormat = new Regex(@"^([0-9\.]+) ([a-z]+) x ([0-9\.]+) ([a-z]+) x ([0-9\.]+) ([a-z]+)( ; ([0-9\.]+) ([a-z]+))?$");
if (rgxFormat.IsMatch(dimensionsString))
{
     //match
}

我不明白代码有什么问题吗?

1 个答案:

答案 0 :(得分:1)

您的模式仅占数字之后的单个单词。在那里允许使用任意数量的符号(带有.*.*?)来修复模式:

^([0-9.]+) (.*?) x ([0-9\.]+) (.*?) x ([0-9.]+) (.*?)( ; ([0-9.]+) (.*))?$

请参见regex demo

请注意,最后一个.*与贪婪的量词一起使用,因为它是字符串中的最后一个未知位(以匹配字符串的所有其余部分)。 .*?是非贪婪版本,与任何字符的出现次数尽可能少,但与换行符匹配。

如有必要,用\s替换常规空格以匹配任何种类的空白。