Allan Jiang
Allan Jiang

Reputation: 11331

regex match hyphen in string

I have a regex \([0-9]+|\-)\ which either takes a number or a hyphen.
but if I use this to match something like -555 it still works because it matches the hyphen-. So I am wondering if there is a way to match the whole thing?

Upvotes: 1

Views: 3117

Answers (1)

mgibsonbr
mgibsonbr

Reputation: 22007

/^([0-9]+|\-)$/

The ^ means "at the beginning of the string line", and the $ means "at its end".

Edit: fixed the answer, thanks to luke-gru. As pointed out in the comments, \A is at the start of the string, \Z is at its end. The behavior of ^ and $ depends on whether multiline is enabled or not.

Upvotes: 8

Related Questions