Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string starts and ends with specific strings?

Tags:

c#

.net

regex

I have a string like:

string str = "https://abce/MyTest";

I want to check if the particular string starts with https:// and ends with /MyTest.

How can I acheive that?

like image 882
Ashish Ashu Avatar asked Nov 28 '22 05:11

Ashish Ashu


1 Answers

This regular expression:

^https://.*/MyTest$

will do what you ask.

^ matches the beginning of the string.

https:// will match exactly that.

.* will match any number of characters (the * part) of any kind (the . part). If you want to make sure there is at least one character in the middle, use .+ instead.

/MyTest matches exactly that.

$ matches the end of the string.

To verify the match, use:

Regex.IsMatch(str, @"^https://.*/MyTest$");

More info at the MSDN Regex page.

like image 169
R. Martinho Fernandes Avatar answered Dec 05 '22 11:12

R. Martinho Fernandes