Regex to match non integers?
Tryin开发者_如何学Gog to create a regex that ignores a proper integer (1
, 5
, 999
, etc.) and forward slashes (/
), but finds a match in everything else. For example, it would find a match the following:
test
test1
test-1
but ignores
1
55
7
This is for a mod rewrite.
[^-0-9\/]+
should do the trick, I think. It'll match any string that contains a non-digit.
Edited to add minus sign which would also be allowed in an integer, and then to include the forward slashes mentioned in the question.
This is a very old question, but I noticed that the currently accepted answer ([^-0-9\/]
) will not match any part of a number string that has a dash/minus (-
) in the middle or at the end or purely consists of dashes.
So the regex will not find a match in strings like 12-34
, 1234-
, --12
, -
, or -----
, even though these are clearly not valid integer numbers and should thus be caught.
To include these in the regex, you can use something like this:
[^-0-9]+|[0-9]+(?=-)|^-$|-{2,}
This will match
- either any part of a string that contains a non-digit, non-minus character (as does the regex from the currently accepted answer)
- or any number that is followed by a minus sign
-
(using a positive lookahead, taking care of the numbers with dashes anywhere but the beginning) - or any string that consists of one single dash
- or any part of a string with two or more consecutive dashes
This will thus find a match in any string that is not a positive or negative integer, see also https://regex101.com/r/8zJwCy/1
To also include (or rather exclude) slashes, as the OP requested, they can be added to the first character group.
[^-0-9\/]+|[0-9]+(?=-)|^-$|-{2,}
Note that this will also not match pure series of slashes (/
, //
, ///
,...) and multiple slashes between integers (1//2
, 1//-2
, //1
, 2//
) which may or may not be desired (the currently accepted answer behaves identically), see https://regex101.com/r/8zJwCy/3
To also catch these, add another two optional groups that match series of slashes, analogous to the last two ones that take care of the dashes. Or, if you want a single individual slash (/
) to be valid, just add one group analogous to the last one, see https://regex101.com/r/8zJwCy/4
[^-0-9\/]+|[0-9]+(?=-)|^-$|-{2,}|\/{2,}
This would match line by line - is that what you need?
^[0-9\/]*$
This should do the job!
^[0-9\/]+$
精彩评论