使用明确编号的重复而不是问号、星号和加号 [英] Using explicitly numbered repetition instead of question mark, star and plus
问题描述
我见过使用明确编号的重复而不是 ?
、*
和 +
的正则表达式模式,即:
I've seen regex patterns that use explicitly numbered repetition instead of ?
, *
and +
, i.e.:
Explicit Shorthand
(something){0,1} (something)?
(something){1} (something)
(something){0,} (something)*
(something){1,} (something)+
问题是:
- 这两种形式是否相同?如果您添加占有/不情愿修饰语会怎样?
- 如果它们是相同的,哪一个更地道?更具可读性?只是更好"?
推荐答案
据我所知,它们是相同的.我认为可能有一些引擎不支持编号语法,但我不确定是哪个.我依稀记得几天前关于 SO 的一个问题,其中显式符号在 Notepad++ 中不起作用.
To my knowledge they are identical. I think there maybe a few engines out there that don't support the numbered syntax but I'm not sure which. I vaguely recall a question on SO a few days ago where explicit notation wouldn't work in Notepad++.
我唯一一次使用明确编号的重复是当重复大于 1 时:
The only time I would use explicitly numbered repetition is when the repetition is greater than 1:
- 正好两个:
{2}
- 两个或更多:
{2,}
- 二到四:
{2,4}
我更喜欢这些,尤其是当重复模式超过几个字符时.如果你必须匹配3个数字,有些人喜欢写:\d\d\d
,但我更愿意写\d{3}
,因为它强调数字涉及的重复.此外,如果该数字需要更改,我只需要将 {3}
更改为 {n}
而不是在我的脑海中重新解析正则表达式或担心搞砸;它需要较少的脑力劳动.
I tend to prefer these especially when the repeated pattern is more than a few characters. If you have to match 3 numbers, some people like to write: \d\d\d
but I would rather write \d{3}
since it emphasizes the number of repetitions involved. Furthermore, down the road if that number ever needs to change, I only need to change {3}
to {n}
and not re-parse the regex in my head or worry about messing it up; it requires less mental effort.
如果不满足该标准,我更喜欢速记.使用显式"符号会很快弄乱模式并使其难以阅读.我曾参与过一个项目,其中一些开发人员不太了解正则表达式(这并不是每个人都喜欢的话题),我看到了很多 {1}
和 {0,1}
出现.一些人会要求我对他们的模式进行代码审查,这时我会建议将这些出现的情况更改为速记符号并节省空间,并且在 IMO 中提高可读性.
If that criteria isn't met, I prefer the shorthand. Using the "explicit" notation quickly clutters up the pattern and makes it hard to read. I've worked on a project where some developers didn't know regex too well (it's not exactly everyone's favorite topic) and I saw a lot of {1}
and {0,1}
occurrences. A few people would ask me to code review their pattern and that's when I would suggest changing those occurrences to shorthand notation and save space and, IMO, improve readability.
这篇关于使用明确编号的重复而不是问号、星号和加号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!