简体   繁体   中英

C# Capturing the first match with regex

I've got an input string that looks like this:

url=https%3A%2F%2Fdomain.com%2Fsale-deal%3Futm_source%3Dinsider-primary-action%3Dinsider-primary-action&utm_source=FB

or

url=https%3A%2F%2Fdomain.com%2Fsale&utm_source=FB&sub_id1=M12

the string sometimes has or non %3Futm_source

how to get link between url= and %3Futm_source% or &utm_source

Regex reg = new Regex(@"url=(https%3A%2F%2Fdomain.com[a-zA-Z0-9-_/%\.]+)%3Futm_source|&utm_source");
                    Match result = reg.Match(inPut);
Console.WriteLine(result.Groups[1].Value));

it always get from url= to &utm_source

You can use this

(?<=url=).*?(?=%3Futm_source|&amp;utm_source)
  • (?<=url=) Positive look behind. matches url= .
  • .* - Matches anything except new line.
  • (?=%3Futm_source|&amp;utm_source) - Positive look ahead. Matches %3Futm_source or &amp;utm_source

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM