1

I have strings that contain URL encoding (%22) and other characters [!@#$%^&*]. I need to use a RegEx to check if the string contains a character within that group but exclude the URL encoded quote (%22). I can't get the negative look ahead to work properly nor am I able to get an excluded string (or negation) working either. Can someone help? Here is code so far that doesn't work:

Pattern p = Pattern.compile("[!@#$%^&*]"); //
String[] tokens = {"%22Hobo%22", "Shoe*", "Rail%6Road","Sugar"};
for (String string : tokens) {
  Matcher m = p.matcher(string);
  boolean b = m.find()
  System.out.println(string + ": " + b);
}

The desired output should be false, true, true, false.

2
  • 1
    Whyo you do not use a URLEncoder? Commented Feb 19, 2015 at 15:49
  • What I put in the example was for ease and readability. Commented Feb 19, 2015 at 16:08

2 Answers 2

3
(?!%22)[!@#$%^&*]

Try this.See demo.

https://regex101.com/r/mS3tQ7/16

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks vks, this is it. I was so close but had a few too many expressions.
0
export const uriParser = (x) =>
  //replace/regex exclude-negated [set-of-tokens], doesn't work/parse for (%[A-Fa-f0-9]{2})+
  //decodeURI() does the same I believe, but this will always return a string,
  //without an error object
  //a-z or A-Z includes underscore '_' but not space whitespace, nor (\r\n|\r|\n)+
  x.replace(/(%[A-Fa-f0-9]{2})+[^a-zA-Z0-9-+ ]+/g, "_");

https://www.ietf.org/rfc/rfc3986.txt#:~:text=2.4.%20%20When%20to%20Encode%20or%20Decode%0A

for my purposes I make my uri link fragmens go thru (%[A-Fa-f0-9]{2})+ on mount so I use .replace("_"," ") for ui but uriParser() for outgoing links in ux to bypass redundancy as much as possible. The use case choice is between getting a string always & putting specifications for other characters before this. "Whyo you do not use a URLEncoder?" – Jens' comment on question

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.