本文介绍了限制正则​​表达式中的字符长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用正则表达式将 正则表达式限制为 100 个字符?

Is there a way to limit a regular expression to 100 characters WITH a regular expression?

\[size=(.*?)\](.*?)\[\/size]

所以 看着我! 行不通.

我想限制数字,只允许 1 到 100 之间的数字.

I want to limit the numbers, only allow numbers between 1 and 100.

推荐答案

您的示例表明您想从正则表达式内部获取一个数字,然后使用此数字将最大长度放置在正则表达式中稍后匹配的另一个部分上.这通常不可能一次性完成.最好的办法是有两个单独的正则表达式:

Your example suggests that you'd like to grab a number from inside the regex and then use this number to place a maximum length on another part that is matched later in the regex. This usually isn't possible in a single pass. Your best bet is to have two separate regular expressions:

  • 一个匹配您想要使用的最大长度
  • 使用之前提取的值来验证自己的匹配没有超过指定的长度

如果只想限制表达式匹配的字符数,大多数正则表达式都支持边界,使用大括号.例如,

If you just want to limit the number of characters matched by an expression, most regular expressions support bounds by using braces. For instance,

\d{3}-\d{3}-\d{4}

将匹配(美国)电话号码:正好三个数字,然后是一个连字符,然后是三个数字,然后是另一个连字符,然后是四个数字.

will match (US) phone numbers: exactly three digits, then a hyphen, then exactly three digits, then another hyphen, then exactly four digits.

同样,您可以设置上限或下限:

Likewise, you can set upper or lower limits:

\d{5,10}

表示至少 5 个,但不超过 10 个数字".

means "at least 5, but not more than 10 digits".

更新: OP 澄清说他试图限制,而不是长度.我的新答案是不要为此使用正则表达式.提取该值,然后将其与您从 size 参数中提取的最大值进行比较.它更不容易出错.

Update: The OP clarified that he's trying to limit the value, not the length. My new answer is don't use regular expressions for that. Extract the value, then compare it against the maximum you extracted from the size parameter. It's much less error-prone.

这篇关于限制正则​​表达式中的字符长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 19:07