开发者

Regular expression: is there a way to set maximum size of pattern?

开发者 https://www.devze.com 2023-01-26 02:04 出处:网络
开发者_运维百科For example, if I have the string: 0123456789 I would write expresion like this: 0.*9 WHERE PATTERN MAX SIZE is 3. in this case, pattern should fail.The specific solution to your examp

开发者_运维百科For example, if I have the string:

0123456789

I would write expresion like this:

0.*9 WHERE PATTERN MAX SIZE is 3. in this case, pattern should fail.


The specific solution to your example is:

/^0.?9$/

The general solution to your abstract question is:

/^(?=.{0,3}$)0.*9$/

In the above (?=.{0,3}$) is a lookahead that the rest of the string has length between 0 and 3.


x{min,max} will match x between min and max times
x{min,} will match x at least min times
x{,max} will match x at most max times
x{n} will match x exactly n times

All ranges are inclusive.

Shortcuts: {0,1} => ?, {0,} => *, {1,} => +.

I'm not sure if this is exactly what you need, but it should help you build your regex.

Example: ^0\d{,3}9$ will match strings with at most 5 digits starting with 0 and ending with 9. Matches: 0339, 06319, 09. Does not match: 033429, 1449.


It sounds like you want to programmatically alter the regex.

Please specify the language you are using (JS, Python, PHP, etc.).

Here's how you could do it using JavaScript:

sYourPattern    = '0.*9';
iPatternMaxSize = 3;

zRegex = new RegExp ('^(?=.{0,' + iPatternMaxSize + '}$)' + sYourPattern + '$');
alert (zRegex.test ('09') );


This gives:

    '9'     --> No match
    '09'    --> Match
    '009'   --> Match
    '0009'  --> No match
    '19'    --> No match
0

精彩评论

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