如何在行的开头_或_结尾处匹配正则表达式? [英] How can I match a regex at the beginning _or_ end of the line?

查看:117
本文介绍了如何在行的开头_或_结尾处匹配正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在行的开头末尾创建一个匹配!next 的JS正则表达式。



目前我正在使用 /(^!next |!next $)/ i 哪个有效。然而,这显然有点难看,而不是干,所以我希望改进。



我最接近的是:



/(?=!next)[^ $] / i



但这实际上只是匹配所有内容(现在我发现我错误地记住了 ^ 在字符类中的工作方式,因此无论如何这个解决方案都是垃圾)。



我在网上搜索了SO,我完全被难倒了。

解决方案

这是一个有趣的,使用正则表达式条件:

  /(^)?! next(?(1)| $) / gm 

Regex101上的演示



它是如何工作的,它捕获了行首锚,如果它不存在,一些人匹配了行尾锚点。



但就个人而言,我仍然赞成你的解决方案而不是我的解决方案,因为它对某些人来说更具可读性一个对正则表达式没有非常全面的了解(并且更便携)的人。



为了增加乐趣,这是另一个版本(甚至比你的初始版本更丑) :

  /!next(?:(?< = ^。{5})|(?= $))/ 
>

=nofollow> Regex101上的演示



我仍然建议坚持使用经典的替代品。



最后,一个在JS中工作的(不,真的):

  /(?:^ | (?=。{5} $))!next / gm 

Regex101上的演示


I'm trying to create a JS regex that matches !next either at the beginning or end of the line.

Currently I'm using /(^!next|!next$)/i which works. However that's obviously kind of ugly to read and not DRY, so I'm looking to improve.

The closest I've come is this:

/(?=!next)[^$]/i

But that actually just matches everything (and it occurs to me now that I misremembered the way that ^ works inside character classes, so this solution is garbage anyway).

I've searched the web and SO, and I'm totally stumped.

解决方案

Here's a fun one, using regex conditionals:

/(^)?!next(?(1)|$)/gm

Demo on Regex101

How it works is it captures the beginning-of-line anchor, and, if it is not present, matches the end-of-line anchor instead.

Personally, though, I'd still argue in favour of your solution over mine because it's more readable to someone who doesn't have an extremely thorough knowledge of regexes (and is more portable).

For added fun, here's another version (that's even uglier than your initial variant):

/!next(?:(?<=^.{5})|(?=$))/gm

Demo on Regex101

I'd still recommend sticking with the classic alternation, though.

And, finally, one that works in JS (no, really):

/(?:^|(?=.{5}$))!next/gm

Demo on Regex101

这篇关于如何在行的开头_或_结尾处匹配正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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