Exclude last regex character

I have the following regex:

%(?:\\.|[^%\\ ])*%([,;\\\s]) 

This works fine, but obviously also highlights the next character with the last % .

I was wondering how can I exclude it from regex?

For example, if I have:

 The files under users\%username%\desktop\ are: 

It will highlight %username%\ , but I just want %username% . On the other hand, if I leave the regex as follows:

 %(?:\\.|[^%\\ ])*% 

... then it will match this pattern that I don't want:

 %example1%example2%example3 

Any idea how to exclude the last character in a match through regex?

+6
source share
2 answers
 %(?:\\.|[^%\\ ])*%(?=[,;\\\s]) ^^ 

Use lookahead . What you need is a 0 width assertion that does not commit anything.

+3
source

You can use a more efficient regular expression than you are currently using. When striping is used with a quantifier, unnecessary backtracking occurs.

If the lines you have are short, it is normal to use. However, if they can be a little longer, you may need to expand the expression.

Here's how to do it:

 %[^"\\%]*(?:\\.[^"\\%]*)*% 

Regular Expression Distribution:

  • % - initial percent sign
  • [^"\\%]* - beginning of the expanded pattern: 0 or more characters, other than double quotation mark, backslash and percent sign
  • (?:\\.[^"\\%]*)* - 0 or more sequences ...
    • \\. - literal backslash followed by any character other than a new line
    • [^"\\%]* - 0 or more characters other than the double quote, backslash, and percent sign
  • % - minus sign

Watch this demo - 6 steps versus 30 steps with %(?:\\.|[^" %\d\\])*% .

+1
source

All Articles