如何将此PHP正则表达式转换为Javascript?

时间:2022-10-30 13:16:06

I tried converting this:

我尝试转换这个:

$regex = "/^[0-9]+[0-9\.]*(?<!\.)$/"

to all of these, but none are correct:

对所有这些,但没有一个是正确的:

var regex = /^(?!\.$)[0-9]+[0-9\.]*/;
var regex = /^(?!.*\.$)[0-9]+[0-9\.]*/;
var regex = /^[0-9]+[0-9\.]*(?!\.$)/;

The PHP regex correctly rejects 1.1a and 1., but the javascript regex's do not.

PHP正则表达式正确拒绝1.1a和1.但javascript正则表达式没有。

1 个解决方案

#1


6  

Your PHP Regex may be better written as the following, which matches the same language, but is easier to read and doesn't need to use a negative look-behind:

您的PHP Regex可能更好地编写如下,它匹配相同的语言,但更容易阅读,不需要使用负面的后视:

$regex = "/^\d+(\.\d+)*$/"

It is also easy to translate it directly to a Javascript regex:

将它直接翻译成Javascript正则表达式也很容易:

var regex = /^\d+(\.\d+)*$/;

#1


6  

Your PHP Regex may be better written as the following, which matches the same language, but is easier to read and doesn't need to use a negative look-behind:

您的PHP Regex可能更好地编写如下,它匹配相同的语言,但更容易阅读,不需要使用负面的后视:

$regex = "/^\d+(\.\d+)*$/"

It is also easy to translate it directly to a Javascript regex:

将它直接翻译成Javascript正则表达式也很容易:

var regex = /^\d+(\.\d+)*$/;