4

I am using the following RegEx to basically filter out any text, and accept numeric + operators.

([-+]?[0-9]*\.?[0-9]+[\/\+\-\*])+([-+]?[0-9]*\.?[0-9]+)

So it grabs 1+1, 1-1, 2*2, 10/2, etc.. Since the solution I am writing doesn't just evaluate the expression on the row, but it totals all calculated rows in a total, I need to allow for users to put stand alone positive/negative numbers that will affect the total (500, -500, +500 (fool proofing)).

Here is the test I've been running. I need to be able to match on the +500, -500, and 500 in the test cases while still excluding any text. I am absolutely terrible with RegEx, so any help is greatly appreciated!

Tushar
  • 85,780
  • 21
  • 159
  • 179
  • Check [`([-+]?[0-9]*\.?[0-9]+[\/\+\-\*])*([-+]?[0-9]*\.?[0-9]+)?`](https://regex101.com/r/pQ5iB3/2) – Tushar Nov 10 '15 at 15:57
  • Possible duplicate of [Reference - What does this regex mean?](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – Kristján Nov 10 '15 at 16:02

2 Answers2

1

If I understand well your purpose, you could just replace the + in the middle to *:

([-+]?[0-9]*\.?[0-9]+[\/\+\-\*])*([-+]?[0-9]*\.?[0-9]+)
1

Your regex requires both groups to be present at least once. You can make the first group optional by changing the + to * to only require a match of the second group and make it a bit shorter like this.

(?:[-+]?\d*\.?\d+[\/*+-])*(?:[+-]?\d*\.?\d+)

See demo at regex101

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
  • I like this a lot. One more question if you don't mind. Is there a way to make the whole match fail if any non-numeric character is entered into the string. Say a user enters '5*5', but then accidentally hits a character before enter and submits '5*5f' as the value. I would like that to return false as well. – user3581440 Nov 10 '15 at 16:19
  • @user3581440 Sure you can just [anchor](http://www.regular-expressions.info/anchors.html) the pattern with `^` start and `$` end anchors [like this](https://regex101.com/r/zK6cL5/1). – bobble bubble Nov 10 '15 at 16:25