sujitgr8
sujitgr8

Reputation: 73

Regex match String with + or - in between

My input is 1+1 or 1-1 or 2+9 or 3-12 or 31-10 or 11+11 and like wise

I tried

^\d*[\+\-]\d*$

It works but what I need is that the input like +1 or +2 or +31 or 1+ or 7+ or -1 or -2 or -31 or 1- or 7- should not match.

Upvotes: 1

Views: 83

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

Replace * with +:

var pat = @"^\d+[+-]\d+$";

See a demo of how this regex works.

The + quantifier will match one or more instances of a digit disallowing input like -, +, 1+ or -2.

Also, you need not escape + or - in the [-+] character class (- does not have to be escaped as it is at its start/end).

Here is a 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);
}

Output:

1+1: True
1-1: True
2+9: True
3-12: True
31-10: True
11+11: True
+1: False
+2: False
+31: False
1+: False
7+: False
-1: False
-2: False
-31: False
1-: False
7-: False

Upvotes: 1

Sahil Gulati
Sahil Gulati

Reputation: 15141

For you input try this one (i.e. Replace your regular expression's * to +)

^\d+[\+\-]\d+$

* denotes zero or more occurrences.

+ denotes one or more occurrences.

Upvotes: 0

lordkain
lordkain

Reputation: 3109

when you also want to match if there is an optional whitespace between 1 and + u can use regex

^\d+\s*[+-]\s*\d+$

look for example at https://regex101.com/r/bpCjKM/2

explanation regex

/
^\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)

Upvotes: 0

Related Questions