PHP Regex: Replace anything that isn't a dot or a digit?
I'm trying to see if a string is an IP address. Since IPv6 is rolling out it's better to support that too, so to make it simple, i just want to replace anything that isn't a dot or a number.
I found this regex on stackoverflow by searching:
\d+(?:\.\d+)+
but it does the opposite of what i want. Is it possible to inverse that reg开发者_如何学Cex pattern?
Thanks!
Try the following:
[^.0-9]+
Matches anything that is not a dot or a number
This regex will match anything that isn't a dot or a digit:
/[^\.0-9]/
I might try something like this (untested):
Edit:
Old regex was way off, this appears to do better (after testing):
find: .*?((?:\d+(?:\.\d+)+|))
replace: $1
do globally, single line.
In Perl: s/.*?((?:\d+(?:\.\d+)+|))/$1/sg
Regex shortcuts are case sensitive. I think you were trying to do something like this, but what you want is capital D
[\D] = any non-digit.
in php it looks like this:
preg_replace('/[\D]/g', '', $string);
javascript its like this:
string.replace(/[\D]/g, '');
精彩评论