简体   繁体   English

仅与这些情况匹配的正则表达式

[英]Regex expression that match only these cases

I have a regular expression in c# that should return IsMatch = true only when the input has the desired pattern but actually is returning true if some of the characters matches...How would be the correct regular expression? 我在C#中有一个正则表达式,仅当输入具有所需的模式时才应返回IsMatch = true,但如果某些字符匹配则实际上返回true ...正确的正则表达式将如何?

Regex reg = new Regex(@"[0-9 \-+]"); //accept only numbers, spaces, minus character and plus character

string formularight="1123 - 4432+32124";//its correct

bool validformat=reg.IsMatch(formularight)) //returns true, ok

string formulawrong="1123a - 4432+32124"; //it has one letter ismatch should be false...

validformat=reg.IsMatch(formulawrong)) //returns true, not ok

I check later if each number is followed by a minus or plus sign before the next number but if it can be included in the regex validation... 稍后我检查每个数字是否在下一个数字之前加上减号或加号,但是否可以将其包含在正则表达式验证中...

I checked other regex questions and before someone suggest that i use a datatable to compute() the expresion or use some calculator logic please know that in this case the numbers are used like fields names that i will use to get some values from the database not numerical values per se. 我检查了其他正则表达式问题,并在有人建议我使用数据表来计算exp()或使用一些计算器逻辑之前,请知道在这种情况下,数字将像字段名一样使用,我将使用它们从数据库中获取一些值,而不是数值本身。 So i only need the regex validation before parsing the formula. 因此,我只需要在解析公式之前进行正则表达式验证即可。 Thanks 谢谢

Valid examples for regex:
11123
112 - 1121
112-1121
1221111+554-111135678
44332-54-114

Invalid examples (letters present, not a + or - between numbers,...):
112 -
6543e
112 1121
6543e + 4432
-7632

Your Regular Expression finds several matches, because you didn't force it to match the whole input. 您的Regular Expression找到多个匹配项,因为您没有强迫它匹配整个输入。

By using the following anchors, it will be forced to check the entire input. 通过使用以下锚点,将被强制检查整个输入。

  • ^ - Start ^ -开始
  • $ - End $ -结束

Regex: 正则表达式:

^[0-9 \-+]*$

Regexr: http://regexr.com/3b97l 正则表达式: http: //regexr.com/3b97l

You should start and end anchors in your regex: 您应该在正则表达式中开始和结束锚点:

Regex reg = new Regex(@"^[0-9 +-]+$");

to make sure whole input matches given set of characters. 确保整个输入匹配给定的字符集。

isMatch Reference isMatch参考

How about: 怎么样:

^\d+(?:\s*[+-]\s*\d+)*$

This works for your valid and invalid examples. 这适用于您的有效和无效示例。

In order to match numbers in brackets: 为了匹配括号中的数字:

^\[?\d+\]?(?:\s*[+-]\s*\[?\d+\]?)*$

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

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