Home > Net >  How to blacklist specific character, but also allow any other character or no character, without usi
How to blacklist specific character, but also allow any other character or no character, without usi

Time:10-15

I'm trying to find a solution to a regex that can match anything after a string or nothing, but if there's something it can't be a dot .

is it possible to do without negative lookahead?

here's an example regex:

.*\.(cpl)[^.].*

now the string:

C:\Windows\SysWOW64\control.exe mlcfg32.cpl sounds

this one is matched, but if there's only:

C:\Windows\SysWOW64\control.exe mlcfg32.cpl

it's not matched because due to the dot blacklist it's searching for any character after cpl,if i use ? after the [^.] however it won't blacklist the . in case there's something else after, so it will capture this even if it shouldn't:

C:\Windows\SysWOW64\control.exe mlcfg32.cpl. sounds

can it be done without using negative lookaheads? - ?!

CodePudding user response:

You may use this regex:

.*\.cpl(?:[^.].*|$)

RegEx Demo

RegEx Breakdown:

  • .*: Match 0 or more of any character
  • \.cpl: Match .cpl
  • (?:[^.].*|$): Match end of string or a non-dot followed by any text

CodePudding user response:

You can use

.*\.(cpl)(?:[^.].*)?$

See the regex demo. Details:

  • .* - zero or more chars other than line break chars as many as possible
  • \. - a dot
  • (cpl) - Group 1: cpl
  • (?:[^.].*)? - an optional non-capturing group that matches a char other than . char and then zero or more chars other than line break chars as many as possible
  • $ - end of string.
  • Related