简体   繁体   English

正则表达式匹配3到4位数字

[英]Regular Expression to match 3 to 4 digits

I am learning regular expressions and I am trying find this string day1otlk_XXXX.gif where the 4 X's will be 3 to 4 random digits. 我正在学习正则表达式,并尝试找到此字符串day1otlk_XXXX.gif,其中4个X将是3到4个随机数字。 This is what I have so far am I close? 到目前为止,这是我要关闭的东西?

qr/day1otlk_\d++\.gif/i

Kinda close. 金田关闭。 You have the \\d for digits. 您有\\d数字。

Do you know what the range operator for regular expressions is? 您知道正则表达式的范围运算符是什么吗?

Very close. 很接近。 This should do it... 这应该做...

day1otlk_\d{3,4}\.gif

The braces {} allow you to specify a ranged number of repeated characters {3,4} or an exact number like {4} . 大括号{}允许您指定一定范围的重复字符{3,4}或精确数字,例如{4}

the regex should be /day1otlk_(\\d{3,4})\\.gif/ , maybe /i for case-insensitivity. 正则表达式应为/day1otlk_(\\d{3,4})\\.gif/ ,对于不区分大小写的情况,可能为/i if it's in a string you might want /\\bday1otlk_(\\d{4})\\.gif\\b/ instead for stuff like "asdjklfhlday1otlk_5242.gifiasdytoi" , which you probably don't want. 如果它在字符串中,则可能需要/\\bday1otlk_(\\d{4})\\.gif\\b/而不希望/\\bday1otlk_(\\d{4})\\.gif\\b/诸如"asdjklfhlday1otlk_5242.gifiasdytoi"类的东西。

the {3,4} means that there need to be between three and four digits, and the parentheses to capture those four digits in \\1 or $1. {3,4}表示必须在三到四位数之间,并且用括号括起来可以用\\ 1或$ 1捕获这四位数。

(bonus un-asked-for answer: if you need exactly three or, say, five, you can't do that. {3,5} will get between three and five. you'd need \\d{3}\\d{2}? or something of the sort.) (未提出答案的奖励:如果您恰好需要三个,或者说五个,则无法做到这一点。 {3,5}将介于三个和五个之间。您需要\\d{3}\\d{2}?还是类似的东西。)

您可以使用大括号指定范围量词:

qr/day1otlk_\d{3,4}\.gif/i

You can specify that there will be 3 or 4 digits with the following: 您可以指定3位或4位数字,并包含以下内容:

day1otlk_\d{3,4}\.gif

The {} is a repetition modifier. {}重复修饰符。 It's a little more precise than * or + . 它比*+更精确。 You can use it to specify an exact number of repetitions of the preceding pattern or a range of repetitions. 您可以使用它来指定前一个模式的确切重复次数或重复范围。

a{m} - exactly m a's a{m} -正好是
a{m,} - at least m a's a{m,} -至少m a
a{m,n} - at least m but at most n a's a{m,n} -至少m个,但最多n个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM