0

I have a multiline text box which contains below string URLs:

http://foodfacts.ambigouos.com
http://articles.ambigouos.com
http://www.dirtshirt.org

I want to replace/update a string http to https from the above URLs which has ambigouos.com as a domain with Regex.

Expected output:

https://foodfacts.ambigouos.com
https://articles.ambigouos.com
http://www.dirtshirt.org

Below code tried but not working:

multilinebox.text = Regex.Replace(multilinebox.text, @"^http?://[a-zA-Z]*(\.ambigouos\.com)$", "$1", RegexOptions.IgnoreCase);

Thanks in advance.

7
  • 2
    Below code tried but not working How specifically is it not working? Commented Mar 6, 2018 at 11:21
  • Can you define not working? Commented Mar 6, 2018 at 11:22
  • 2
    You're aware that your regex matches http:// or htt://, right? Commented Mar 6, 2018 at 11:23
  • 3
    you might not need regexp, just check if line .Contains("ambigouos.com") and then do .Replace("http://", "https://") Commented Mar 6, 2018 at 11:25
  • @trailmax That is true if only OP does not want to make sure only an HTTP link is changed. Commented Mar 6, 2018 at 11:26

1 Answer 1

2

You may leverage the fact that the strings are at the start of a line (i.e. you should compile the regex with the RegexOptions.Multiline flag), you do not need to check the end of the string/line here. Also, you need to set the grouping construct around the whole non-fixed part of the string.

If you need to only handle matches at the start of a line use

Regex.Replace(multilinebox.text, @"^http://((?:[^/]*\.)?ambigouos\.com)", "https://$1", 
     RegexOptions.IgnoreCase | RegexOptions.Multiline);

If you want to handle matches anywhere inside a string remove ^ and | RegexOptions.Multiline use

Regex.Replace(multilinebox.text, 
          @"http://((?:[^/]*\.)?ambigouos\.com)", 
          "https://$1", 
          RegexOptions.IgnoreCase);

See the regex demo.

Detasils

  • ^ - start of a line (since RegexOptions.Multiline is used)
  • http:// - a literal substring
  • ((?:[^/]*\.)?ambigouos\.com) - Capturing group 1:
    • (?:[^/]*\.)? - an optional sequence of any 0+ chars other than /, and then a .
    • ambigouos\.com - a literal substring.

You may add \r\n to the negated character class to avoid overflowing across lines, i.e. [^/] => [^/\r\n].

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

7 Comments

http://foodfacts.ambigouos.com/ is not matching with the above regex hence not replacing to https://foodfacts.ambigouos.com/ suggest!!
@PPB Do you mean to say you do not need to match these URLs at the start of a line but anywhere inside the string?
@PPB But that means you want to match http:// at the start of a line. There is no need removing ^ start-of-line anchor. Have you added the RegexOptions.Multiline option? Show the exact code you have at IDEONE.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.