10

I have the following regex:

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

That works great but obviously it also highlights the next character to the last %.

I was wondering how could I exclude it from the regex?

For instance, 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 like this:

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

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

%example1%example2%example3

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

3
  • I think I found a solution with a brand new RegEx... sorry for posting this too early! This does what I need... %(?:\\.|[^" %\d\\])*% Nov 12, 2015 at 21:13
  • This regex is not effecient, as you have an alternation group with a quantifier applied. If it is not an issue (the strings you have a short) it is OK. If they can be a bit longer, you need to unroll it. See this demo - 6 steps vs. 30. Nov 12, 2015 at 21:18
  • Did any of the answers help? Please consider accepting the one that works best for you. Jan 3, 2021 at 1:45

2 Answers 2

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

                   ^^

Use a lookahead.What you need here is 0 width assertion which does not capture anything.

4

You can use a more effecient regex than you are currently using. When alternation is used together with a quantifier, there is unnecessary backtracking involved.

If the strings you have are short, it is OK to use. However, if they can be a bit longer, you may need to "unroll" the expression.

Here is how it is done:

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

Regex breakdown:

  • % - initial percentage sign
  • [^"\\%]* - start of the unrolled pattern: 0 or more characters other than a double quote, backslash and percentage sign
  • (?:\\.[^"\\%]*)* - 0 or more sequences of...
    • \\. - a literal backslash followed by any character other than a newline
    • [^"\\%]* - 0 or more characters other than a double quote, backslash and percentage sign
  • % - trailing percentage sign

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.