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?
To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself. The character '.
The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.
$ means "Match the end of the string" (the position after the last character in the string).
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.
%(?:\\.|[^%\\ ])*%(?=[,;\\\s])
^^
Use a lookahead
.What you need here is 0 width assertion
which does not capture anything.
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 signSee this demo - 6 steps vs. 30 steps with your %(?:\\.|[^" %\d\\])*%
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With