正则表达式 - 连字符应该被转义吗? [英] Regex - Should hyphens be escaped?

查看:34
本文介绍了正则表达式 - 连字符应该被转义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何用正则表达式匹配连字符?

连字符是正则表达式中的一个特殊字符,例如,要选择一个范围,我可以这样做:

Hyphen is a special character in regex, for instance, to select a range, I could do something like:

[0-9A-F]

但是在方括号之外它只是一个普通字符,对吗?我已经在几个在线正则表达式测试器上对此进行了测试,连字符似乎可以作为方括号外的普通字符(如果不在两个字符之间,甚至在方括号内 - 例如 [-g] 似乎匹配- 或 g) 它是否被转义.我找不到这个问题的答案,但我想知道逃避连字符是否是惯例.

But outside of square brackets it's just a regular character right? I've tested this on a couple of online regex testers, and hyphens seem to function as a normal character outside of square brackets (or even inside of square brackets if it's not in-between two characters - eg [-g] seems to match - or g) whether it's escaped or not. I couldn't find the answer to this, but I'm wondering whether or not it is conventional to escape hyphens.

谢谢!

推荐答案

各方面都正确.在字符类之外(这就是所谓的方括号"),连字符没有特殊含义,在字符类中,您可以将连字符作为范围内的第一个或最后一个字符(例如 [-az][0-9-]),OR 转义它(例如 [az\-0-9])以便在您的班级中添加连字符".

Correct on all fronts. Outside of a character class (that's what the "square brackets" are called) the hyphen has no special meaning, and within a character class, you can place a hyphen as the first or last character in the range (e.g. [-a-z] or [0-9-]), OR escape it (e.g. [a-z\-0-9]) in order to add "hyphen" to your class.

在字符类中找到放在第一个或最后一个连字符的情况更为常见,但绝不会因为您选择逃避它而被成群结队的愤怒的颈须私刑.

It's more common to find a hyphen placed first or last within a character class, but by no means will you be lynched by hordes of furious neckbeards for choosing to escape it instead.

(实际上......我的经验是很多正则表达式被那些不完全理解语法的人使用.在这些情况下,你通常会看到所有东西都被转义了(例如 [az\%\$\#\@\!\-\_]) 只是因为工程师不知道什么是特殊的",什么不是......过多的反斜杠.在使用正则表达式之前花时间真正了解正则表达式的语法,这将对您自己、您的同时代人和您的后代大有帮助.)

(Actually... my experience has been that a lot of regex is employed by folks who don't fully grok the syntax. In these cases, you'll typically see everything escaped (e.g. [a-z\%\$\#\@\!\-\_]) simply because the engineer doesn't know what's "special" and what's not... so they "play it safe" and obfuscate the expression with loads of excessive backslashes. You'll be doing yourself, your contemporaries, and your posterity a huge favor by taking the time to really understand regex syntax before using it.)

好问题!

这篇关于正则表达式 - 连字符应该被转义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆