简体   繁体   English

如何在行首_or_末尾匹配正则表达式?

[英]How can I match a regex at the beginning _or_ end of the line?

I'm trying to create a JS regex that matches !next either at the beginning or end of the line. 我正在尝试创建与!next匹配的JS正则表达式,无论该行的开头还是结尾。

Currently I'm using /(^!next|!next$)/i which works. 目前,我正在使用/(^!next|!next$)/i However that's obviously kind of ugly to read and not DRY, so I'm looking to improve. 但这显然是丑陋的阅读而不是DRY,所以我正在寻求改进。

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 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 Regex101上的演示

I'd still recommend sticking with the classic alternation, though. 不过,我仍然建议您坚持经典交替。

And, finally, one that works in JS (no, really): 最后,一个可以在JS中运行的代码(不,实际上):

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

Demo on Regex101 Regex101上的演示

You could try 你可以试试

function beginningOrEnd(input, search) {
  const pos = input.search(search);
  return pos === 0 || pos === input.length - search.length;
}

beginningOrEnd("hey, !help", "!help");

This uses search.length , so obviously search must be a string. 它使用search.length ,因此显然search必须是字符串。

Or, you could construct the regexp yourself: 或者,您可以自己构造正则表达式:

function beginningOrEnd(search) {
  return new RegExp(`^${search}|${search}\$`, "i");
}

beginningOrEnd("!help").test(input)

In the real world, you'd want to escape special regexp characters appropriately, of course. 当然,在现实世界中,您希望适当地转义特殊的regexp字符。

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

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