0

Regex is hard :)

What I have right now is a string value that I am succesfuly matching values on specific keys. I need to expand my regex to match a using a value rather than a key.

https://www.me.com/?name=bob&identify=bob1&test=email@me.com&validKey=validValue

The current Regex being applied is

((name|identify|test)(=|%3D)[^&]*)

What I want to add/extend is to match any values that contain an @ symbol. I wont know what the 'key' is in as its dynamic so I cant just add 'badKey' into the matched pattern. So an example input for this would be:

https://www.me.com/?name=bob&identify=bob1&test=email@me.com&validKey=validValue&badKey=test2@test.com

Basically I want to match all the existing parts and then also the 'badKey' one. I know I can run the string through a second Regex but for performance sake I would like this to be a single pattern.

Any help here would be appreciated.

Jacques Ramsden
  • 801
  • 5
  • 20
  • You've tagged C#, so is there a reason you're using Regex rather than [parsing the query string](https://stackoverflow.com/a/659929/8126362)? – Johnathan Barclay Feb 15 '23 at 09:11
  • @JohnathanBarclay This input string was just an example it may not always be a URI. I need similar logic in several places. I was hoping for a resolution on this one and I could then understand how its done on a URI and then apply the logic elsewhere. – Jacques Ramsden Feb 15 '23 at 09:13

2 Answers2

0

I found a pattern that will match specifically emails and not just values that contain an @ symbol

(name|identify|test)(=|%3D)[^&|^%26]*|((=|%3D)(\\w+([-+.]\\w+)*[@|%40]\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*)[^&|^%26]*)
Jacques Ramsden
  • 801
  • 5
  • 20
-1

U can use the String.Split to break down by key=value pairs (split by "&") and processing each pair

Dimitry
  • 128
  • 1
  • 1
  • I asked specifically for Regex. In my case if I had to break down each and every string the overhead would be too much. The Regex ends up being much more efficient. – Jacques Ramsden Feb 16 '23 at 13:33
  • Hmm... IMHO regular expression is not so effective, but.... Then I would use something like this: [?&](\w+)\=([^&]+) – Dimitry Feb 16 '23 at 14:57
  • Hi @Dimitry, that Regex will find everything between the & symbols and not just the bad actor values I want to exclusively look for. But thanks for trying. Also Regular expressions definitely have their place else they wouldn't exist or be supported. In my case I need to use one as it is more efficient than normal string functions. – Jacques Ramsden Feb 17 '23 at 20:12
  • Just a side note if you read my question I am looking for keys that have specific values and then also specifically any value that is an email not just things between the Amp symbol – Jacques Ramsden Feb 17 '23 at 20:22