简体   繁体   English

正则表达式-必须以某些字符开头,但不能包含此字符串

[英]Regex - Has to start with certain characters but can't contain this string

I have this regex that I been using, but now I need to add something to it. 我已经使用了这个正则表达式,但是现在我需要为其添加一些内容。

^[|a-z-&+\/](?!\|)

I tried a few things, but I just can't come up with the solution. 我尝试了一些方法,但是我无法提出解决方案。

I want it to add to it, to not match anything that contains a "##" in any position. 我希望它添加到它,不匹配任何位置包含“ ##”的任何内容。

These match: 这些匹配:

|test
test#test
apple

These don't match: 这些不匹配:

||test
test##test
apple##

One option is to add a negative lookahead at the beginning after the ^ anchor: (?!.*##) . 一种选择是在^锚之后的开头添加负前瞻: (?!.*##)

Example Here 这里的例子

^(?!.*##)[|a-z-&+\/](?!\|)

As Casimir et Hippolyte points out , since # can't be the first character, you could alternatively add this check as an alternation in the existing lookahead: 正如Casimir et Hippolyte指出的那样 ,由于#不能是第一个字符,因此您可以选择将此检查添加为现有前瞻的替代形式

Example Here 这里的例子

^[|a-z-&+\/](?!\||.*##)

Explanation: 说明:

  • ^[|az-&+\\/] - Match a single character in the character set at the start of the string (or line if you're using the multi-line flag). ^[|az-&+\\/] -匹配字符串开头(如果使用多行标志,则为行)开头的字符集中的单个字符。
  • (?! - Start of a negative lookahead (?! -负前瞻的开始
  • \\| - Match the | -匹配| character literally 字面上的字符
  • | - Alternation; -交替; or.. 要么..
  • .*## - Check for the ## characters .*## -检查##字符
  • ) - Close the negative lookahead ) -关闭负面的前瞻

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

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