简体   繁体   中英

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:

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).
  • (?! - Start of a negative lookahead
  • \\| - Match the | character literally
  • | - Alternation; or..
  • .*## - Check for the ## characters
  • ) - Close the negative lookahead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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