Okay, I have a problem with regexp and '%'

I am trying to set up a pattern to perform validation of a string. But I seem to have a problem with the '%" character.

Backing up a bit if I use this pattern ^\d+a?$ it matches 22 and 22a but not 22aa. That's fine, but I don't want to test for 'a' I want to test for '%'

So with the pattern ^\d+%?$ (swapping in '%' for 'a')I find that 2% matches, 2%%% does not but 2%% matches but it should not.

It seems the '%' character has nuances I'm not aware of. Any ideas, anyone? Thanks!

Where are you seeing it match 2%%? I see only the 2% matching, not either of the others.

^ = from beginning of line
\d+ = one or more digits
%? = match a % sign, either 0 or 1 times (i.e. optional)
$ = end of line

When I put that in my tester (I'm using Patterns on macOS), it does what I'd expect:



What the problem that you are trying to solve by validating this class of strings ?

(Do you think it's possible that Keyboard Maestro token-processing, or percent-encoding and decoding in the context of URLs, is adding a layer of complexity here ?)

The adjacent \d makes me wonder if you are looking at this kind of thing:

Percent-encoding - MDN Web Docs Glossary: Definitions of Web-related terms | MDN

Bingo! I didn't even think about this last night, but that's the problem. Here's a simple test macro:

Download Macro(s): Test RegEx.kmmacros (5.2 KB)

Macro screenshot

Macro notes
  • Macros are always disabled when imported into the Keyboard Maestro Editor.
    • The user must ensure the macro is enabled.
    • The user must also ensure the macro's parent macro-group is enabled.
System information
  • macOS 14.5
  • Keyboard Maestro v11.0.3

The macro has two variables, one with token processing disabled in the Gear menu, the other with it set to normal processing. When run, the output is this:

You can see that the token processing is turning 2%% into 2%. @ComplexPoint is spot on: Disable token processing where you're setting the variable with the percentage signs, and it should work.



( and, of course, if the material does, in fact, involve percent-encoded url strings, then there may be a simpler route which passes through Percent Decode URL in a Keyboard Maestro filter action )

1 Like

Thank you both very much! I have run into problems using '%' before, but didn't realize exactly why. Nor did I know you can disable token processing. This is great, thanks again.