sailboatlie
sailboatlie

Reputation: 346

Regular expression to match non-integer values in a string

I want to match the following rules:

I currently have the following regex pattern, I'm matching the inverse so that I can thrown an exception upon finding a match that doesn't follow the rules:

[^-0-9]

The downside to this pattern is that it works for all cases except a hyphen in the middle of the String will still pass. For example:

"-2304923" is allowed correctly but "9234-342" is also allowed and shouldn't be.

Please let me know what I can do to specify the first character as [^-0-9] and the rest as [^0-9]. Thanks!

Upvotes: 0

Views: 2984

Answers (4)

Plynx
Plynx

Reputation: 11461

For a regular expression like this, it's sometimes helpful to think of it in terms of two cases.

  • Is the first character messed up somehow?
  • If not, are any of the other characters messed up somehow?
  • Combine these with |

 (^[^-0-9]|^.+?[^0-9])

enter image description here

Upvotes: 0

dawg
dawg

Reputation: 103874

You can do this:

(?:^|\s)(-?\d+)(?:["'\s]|$)

 ^^^^^                        non capturing group for start of line or space
         ^^^^^                capture number
                 ^^^^^^^^^    non capturing group for end of line, space or quote 

See it work

This will capture all strings of numbers in a line with an optional hyphen in front.

-2304923"  "9234-342"   1234 -1234 
++++++++                                   captured
            ^^^^^^^^                       NOT captured
                        ++++               captured
                             +++++         captured

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213261

I don't understand how your pattern - [^-0-9] is matching those strings you are talking about. That pattern is just the opposite of what you want. You have simply negated the character class by using caret(^) at the beginning. So, this pattern would match anything except the hyphen and the digits.

Anyways, for your requirement, first you need to match one hyphen at the beginning. So, just keep it outside the character class. And then to match any number of digits later on, you can use [0-9]+ or \d+.

So, your pattern to match the required format should be:

-[0-9]+  // or -\d+

The above regex is used to find the pattern in some large string. If you want the entire string to match this pattern, then you can add anchors at the ends of the regex: -

^-[0-9]+$

Upvotes: 1

mvp
mvp

Reputation: 116197

This regex will work for you:

^-?\d+$

Explanation: start the string ^, then - but optional (?), the digit \d repeated few times (+), and string must finish here $.

Upvotes: 2

Related Questions