0

I've been testing a regex of mine. The goal is getting a concrete and named url parameter from a website for replacing it.

Now I almost achieved to get the parameter with this regex:

.website.com.+tag=(?P<tagvalue>.+&|.+\s)

This works fine when the tag is at the end but it gets the value for 'tag' with a trailing '&' like 'value&' when it's in the middle.

I want to get the value but not capturing the ampersand. I tried to extract the termination characters out of the named group like this:

.website.com.+tag=(?P<tagvalue>.+)&|\s

but this regex doesn't work. It always gets until end of line. I want:

  1. Check if there is a '&' character . If it is, capturing the parameter value without '&'
  2. If 1 is not true and there is not a '&' character, then capture the value until end of line (I think this until a \s, because I'm processing text and the url comes inside it).

You can test the regex with some test text here:

https://regex101.com/r/mWetmI/1

6
  • 2
    Why don't you simply use [^&]+? Commented Mar 19, 2018 at 13:51
  • 3
    Does it have to be regex? Python has urlparse Commented Mar 19, 2018 at 13:52
  • 1
    Try .website.com.+tag=(?P<tagvalue>[^&\s]+). But like Mike said, you're better off using the urlparse library Commented Mar 19, 2018 at 13:54
  • 1
    in python 3 its called urllib.parse Commented Mar 19, 2018 at 13:56
  • @MikeScotty With a regex I can make the replacement in one line and I'm familiar with them. Also I don't import more modules. Commented Mar 19, 2018 at 14:29

2 Answers 2

1

You can accomplish that with the following regex:

.website.com.+tag=(?P<tagvalue>[^&\s]+)

This will capture the values for the tag up to but not including the next & or whitespace

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

Comments

0

Try with lazy repetition:

.website.com.+tag=(?P<tagvalue>.+?)(:?\s|&)

https://regex101.com/r/mWetmI/2

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.