RegEx for string starts with number and followed by + character

Viewed 1426

I want a regular expression for such inputs:

1+2
3
1+22+3

But If I write following inputs then it should not allow. Such as;

+1+2
1+
a+1+b+c
12+

The string must start with number and then followed by only + character. But After the + character, it has to be any number. I tried this [^0-9][^+]? but İt deletes the + sign at the start with the regex I wrote, but there is a problem. While deleting the + character, it also removes the number next to it. This event keeps repeating.

How can I do this?

2 Answers

Please try :

\d+(\+\d)*

Demo: https://regex101.com/r/hfqmYr/2

Where:

\d -> Matches with any digit

+ -> Matches a symbol one or more times

* -> Matching a symbol 0 or many times

As mentioned in the comments, it looks like you can use:

^[0-9]+(?:\+[0-9]+)*$

This is to allow the mentioned sample data and discard those you don't want to allow. See an online demo. The pattern matches:

  • ^ - Start line anchor.
  • [0-9]+ - 1+ Digits (ASCII).
  • (?:\+[0-9]+)* - 0+ Times a non-capture group to allow for a literal plus followed by 1+ digits (ASCII).
  • $ - End line anchor.

As per my knowledge .NET requires you to explicitly mention these ASCII digits to avoid matching numbers from other languages (unless specified otherwise using ECMAScript options).

Related