Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - If contains '%', can only contain '%20'

Tags:

regex

I am wanting to create a regular expression for the following scenario:

If a string contains the percentage character (%) then it can only contain the following: %20, and cannot be preceded by another '%'.

So if there was for instance, %25 it would be rejected. For instance, the following string would be valid:

http://www.test.com/?&Name=My%20Name%20Is%20Vader

But these would fail:

http://www.test.com/?&Name=My%20Name%20Is%20VadersAccountant%25

%%%25

Any help would be greatly appreciated,

Kyle


EDIT:

The scenario in a nutshell is that a link is written to an encoded state and then launched via JavaScript. No decoding works. I tried .net decoding and JS decoding, each having the same result - The results stay encoded when executed.

like image 839
Kyle Rosendo Avatar asked Dec 02 '09 09:12

Kyle Rosendo


People also ask

Can I use regex in string contains?

String. contains works with String, period. It doesn't work with regex. It will check whether the exact String specified appear in the current String or not.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

How do you check if a string contains a substring regex?

RegExp provides more flexibility. To check for substrings in a string with regex can be done with the test() method of regular expression. This method is much easier to use as it returns a boolean.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .


2 Answers

Doesn't require a %:

/^[^%]*(%20[^%]*)*$/
like image 81
Mark Byers Avatar answered Sep 20 '22 17:09

Mark Byers


Which language are you using?

Most languages have a Uri Encoder / Decoder function or class. I would suggest you decode the string first and than check for valid (or invalid) characters.

i.e. something like /[\w ]/ (empty is a space)

With a regex in the first place you need to respect that www.example.com/index.html?user=admin&pass=%%250 means that the pass really is "%250".

like image 28
Jürgen Steinblock Avatar answered Sep 19 '22 17:09

Jürgen Steinblock