Regex start and end with specific char, then exclude string between

Viewed 75

I'm trying to figure out how to exclude a specific string from a url link between two characters. In this case variable test. Then end on first " character.

<a href="/?q=test&parameter1&parameter2" ...more content

So far I built this Regex expression:

(?<=[?]q=)[^"]*

TEST

Required result:

<a href="/?q=test &parameter1&parameter2 " ...more content

Thank you!

2 Answers

Use look arounds to match between test and ", where test is a whole word (eg not testing) and is a query param (preceded by = or &, so order of params doesn’t matter):

(?<=[=&]test\b).*?(?=")

See live demo.

Then use your (unspecified) language/tool to replace matches with blank.

To match everything not test in params, ie other params preceding or followingtest too:

(?<=q=).*?(?=\btest\b)|(?<=[=&]test\b).*?(?=")

See live demo.

You can use

(\?q=[^&]*)&[^"]*

and replace with $1. See the regex demo and the regex graph:

enter image description here

Details

  • (\?q=[^&]*) - Capturing group 1: ?q= text and then any zer or more chars other than &
  • & - a literal & char
  • [^"]* - zero or more chars other than a ".
Related