我的输入为1+1
或1-1
或2+9
或3-12
或31-10
或11+11
,同样明智
我试过
^\d*[\+\-]\d*$
它有效,但我需要的是输入,如+1
或+2
或+31
或1+
或7+
或-1
或-2
或-31
或1-
或7-
不匹配。
答案 0 :(得分:1)
将*
替换为+
:
var pat = @"^\d+[+-]\d+$";
查看demo of how this regex works。
+
量词将匹配一个或更多数字不允许输入的实例,例如-
,+
,1+
或{{1 }}
此外,您无需在-2
字符类中转义+
或-
([-+]
不必在其开始/结束时进行转义)
这是C# demo:
-
输出:
var strs = new string[] {"1+1","1-1","2+9","3-12","31-10","11+11","+1","+2","+31","1+","7+","-1","-2","-31","1-","7-"};
foreach (string s in strs)
{
var matched = Regex.IsMatch(s, @"^\d+[+-]\d+$");
Console.WriteLine("{0}: {1}", s, matched);
}
答案 1 :(得分:0)
当你想要匹配时,如果1和+之间有一个可选的空格,你可以使用正则表达式
^\d+\s*[+-]\s*\d+$
在https://regex101.com/r/bpCjKM/2
查找示例解释正则表达式
/
^\d+\s*[\+\-]\s*\d+$
/
g
^ asserts position at start of the string
\d+ matches a digit (equal to [0-9])
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
\s* matches any whitespace character (equal to [\r\n\t\f\v ])
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Match a single character present in the list below [\+\-]
\+ matches the character + literally (case sensitive)
\- matches the character - literally (case sensitive)
\s* matches any whitespace character (equal to [\r\n\t\f\v ])
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\d+ matches a digit (equal to [0-9])
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)
Global pattern flags
g modifier: global. All matches (don't return after first match)
答案 2 :(得分:0)
对于你的输入尝试这个(即将正则表达式的*
替换为+
)
^\d+[\+\-]\d+$
*
表示零次或多次出现。
+
表示一次或多次出现。