[英]Perl. Regex not matching desired when using {x,y} metacharacter
我正在嘗試使用{x,y}
元字符,所以請幫助理解原因
1. 'Hello' =~ /\w{2,}/; # Returns true. while..
2. 'Hello' =~ /\w{,6}/; # ..returns false ??!
\\w{2,}
代表*'匹配[0-9A-Za-z_]字符至少2次'*
\\w{,6}
代表*'匹配[0-9A-Za-z_]字符最多6次'*
如果我讀這個正確嗎? 那么為什么第二個不匹配呢?
根據perlre文檔 - 量詞 ,只有*
, +
, ?
, {n}
, {n,}
, {n,m}
被識別:
以下標准量詞得到認可:
* Match 0 or more times + Match 1 or more times ? Match 1 or 0 times {n} Match exactly n times {n,} Match at least n times {n,m} Match at least n but not more than m times
- > /{,6}/
匹配'{,6}'
字面意思。
根據需要使用/\\w{0,6}/
或/\\w{1,6}/
。
{n,m}
表達式的第一個參數是必需的。 請參閱perlre
手冊頁,例如:
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times
像{,m}
這樣的模式無法識別。 如果你明確地將第一個參數賦予1它的工作原理:
print 'Hello' =~ /\w{1,6}/;
生成“1”。
其實:
\\w{n,m}
表示最少n次匹配字母數字,但最多m次。
\\w{n,}
表示匹配字母數字n次或更多次。
\\w{n}
表示完全匹配字母數字n次。
但是 :
\\w{,m}
表示匹配字母數字后跟文字{,m}
。 這是因為n是必需的; 你必須指定{n,m}
表達式的第一個參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.