开发者

how to do the regexp in javascript for this string?

I have the following possible string: '', or '4.', or '*.4' or '4.35' all the above format are valid, others are开发者_如何学C all invalid. basically, if I don't care the digit or word character, this is what I used in PHP for the validation:

        else if ( !ereg('^\*|.*\..*$',$bl_objver) )

Now, I would like to add some clientside validation, so I just translate it into javascript:

    var ver_reg = new RegExp("^\*|.*\..*$");
    if (ver_reg.test(obj_ver) == false)

but firebug always shows some error, like: "invalid quantifier |...*$" etc..

any suggestions?


(I'm not convinced your expression is correct, but for the moment just going with what you have.)

Using the RegExp object, you need to escape the slashes:

var ver_reg = new RegExp("^\\*|.*\\..*$");

Alternatively you can use regex literal notation:

var ver_reg = /^\*|.*\..*$/;


That answers your direct question, but...

As for the expression, well, what you definitely want to correct is the start/end anchors each applying to one side of the alternation.

i.e. you're saying <this>|<that> where <this> is ^\* and <that> is .*\..*$

What you want is ^(?:<this>|<that>)$ to ensure the start/end markers are not part of the alternatives (but using ?: since we're not capturing the group).

So /^(?:\*|.*\..*)$/ using the second example above - this fix would also need applying to the PHP version (which can use the same syntax).

I'd also question your use of . instead of \w or [^.] or similar, but without knowing what you're actually doing, I can't say for sure what makes most sense.

Hope this helps! :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜