正则表达式为n个字符或至少m个字符 [英] regex for n characters or at least m characters

查看:236
本文介绍了正则表达式为n个字符或至少m个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该是一个很简单的正则表达式问题,但我找不到任何答案。如何做一个正则表达式,只匹配2个字符,或至少4个字符。这是我当前的方法(忽略正则表达式本身,除了点):

This should be a pretty simple regex question but I couldn't find any answers anywhere. How would one make a regex, which matches on either ONLY 2 characters, or at least 4 characters. Here is my current method of doing it (ignore the regex itself, that's besides the point):

[A-Za-z0_9_]{2}|[A-Za-z0_9_]{4,}

两倍的时间(对于我在一个400行文件慢约0.3s),所以我想知道是否有一个更好的方法来做。

However, this method takes twice the time (and is approximately 0.3s slower for me on a 400 line file), so I was wondering if there was a better way to do it?

推荐答案

优化开始并锚定。

^[A-Za-z0-9_]{2}(?:|[A-Za-z0-9_]{2,})$

(还有,你说过忽略正则表达式本身,但我猜你可能想要 0-9 ,而不是 0_9

(Also, you did say to ignore the regex itself, but I guessed you probably wanted 0-9, not 0_9)

EDIT Hm,我确定我读到您要匹配。如果你想在线内匹配,删除锚( ^ $ )。如果你只匹配全线,锚点会加快你的速度(好,前锚 ^ 会,至少)。

EDIT Hm, I was sure I read that you want to match lines. Remove the anchors (^$) if you want to match inside the line as well. If you do match full lines only, anchors will speed you up (well, the front anchor ^ will, at least).

这篇关于正则表达式为n个字符或至少m个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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