开发者

RegEx for 1-6 digits followed by .nn

I'm using JavaScript and would be grateful for a pattern that matches 1 through 6 digits followed by an optional .nn.

So, in the end I'd like to have a function that returns True for strings that match the patterns like these:

nn
nnn
nn.nn
nnnnn.nn
nnnn
nnnnnn.nn
nnnnn开发者_如何学Pythonn

(where n is a digit).

Thanks!!


You can do this with /^\d{1,6}(.\d\d)?$/ so the js would look like:

/^\d{1,6}(\.\d\d)?$/.test(str)


The following will work:

^[0-9]{1,6}(\.[0-9][0-9])?$

You could use \d instead of [0-9] in modern regex engines, I'm just allowing for the lowest common denominator). In other words, this is equivalent to:

^\d{1,6}(\.\d\d)?$

The {1,6} bit is how you specify that the previous match is to occur 1 thru 6 times inclusive, and the X? is the same as X{0,1} (in other words, (\.[0-9][0-9])? means that the period followed by exactly two digits can occur exactly zero or one time).


try this regex:

/\d{1,6}(?:\.\d\d)?/

EDIT:

Based on comments from @Justin here is the enhanced reges:

/(?:^|\b)\d{1,6}(?:\.\d\d)?(?:\b|$)/

To make sure only this number is matched separated by word boundaries.


Try the following: \w{1,6}(\.nn){0,1}

You say digits, but show nnnn.nn. The above is for the example nnnn.nn, but you can change for numerical digits easily by:

\d{1,6}(\.nn){0,1}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜