对于数字范围和人物正则表达式 [英] Regular Expressions for number range and characters

查看:106
本文介绍了对于数字范围和人物正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个号的组合相匹配的正则表达式(大于5,但小于500)与数之后,是文本字符串

I need a regular expression that matches a combination of a number (larger than 5, but smaller than 500) and a text string that comes after the number.

例如,下面的比赛将返回true:6项或450项或300项红色(也可以是单词项目后的其它字符)

For example, the following matches would return true: 6 Items or 450 Items or 300 Items Red (there can be other characters after the word "Items")

而下面字符串将返回false:4项或501项,40项红

Whereas the following strings would return false: 4 Items or 501 Items or 40 Red Items

我试过以下的正则表达式,但它不工作:

I tried the following regex, but it doesn't work:

string s = "Stock: 45 Items";          
Regex reg = new Regex("5|[1-4][0-9][0-9].Items");
MessageBox.Show(reg.IsMatch(s).ToString());



感谢您的帮助。

Thanks for your help.

推荐答案

这正则表达式应该检查工作,如果数在5〜500:

This regex should work for checking if number is in range from 5 to 500:

"[6-9]|[1-9][0-9]|[1-4][0-9][0-9]|500"

修改:例如使用更复杂的正则表达式,其中不包括数字比1000过大,以及一些经过排除比项目等字符串如下:

Edit: below example with more complex regex, which excludes numbers greater than 1000 too, and excludes strings other than " Items" after a number:

string s = "Stock: 4551 Items";
string s2 = "Stock: 451 Items";
string s3 = "Stock: 451 Red Items";
Regex reg = new Regex(@"[^0-9]([6-9]|[1-9][0-9]|[1-4][0-9][0-9]|500)[^0-9]Items");

Console.WriteLine(reg.IsMatch(s).ToString()); // false
Console.WriteLine(reg.IsMatch(s2).ToString()); // true
Console.WriteLine(reg.IsMatch(s3).ToString()); // false

这篇关于对于数字范围和人物正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆