tags:

views:

172

answers:

6
+4  Q: 

How to use RegEx?

Hi,

I haven't used RegEx so please excuse me...

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?

+16  A: 

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.

Martinho Fernandes
+1 U beat me to it.
Stevo3000
+1 For a nice breakdown of the parts :)
Zhaph - Ben Duguid
@Steve3000: Finally! I spent the last three hours being "beaten to it" :)
Martinho Fernandes
Don't see why this isn't the accepted answer, was first and correct!
Stevo3000
@Stevo: thanks for the support. Actually it is not completely correct. There is an extra slash somewhere. Will fix...
Martinho Fernandes
@Stevo3000: It was indeed correct, though mine provided the actual code required to run the match (and was probably higher voted for this reason). Seems the OP switched his accepted answer, anyway. :P
Noldorin
@Noldorin: you are right. My code was added later on, when I noticed the .net tag. FWIW I had upvoted you before.
Martinho Fernandes
@Noldorin - I upvoted you too as you were the first to show the .NET syntax.
Stevo3000
+9  A: 

Try the following:

var str = "https://abce/MyTest";
var match = Regex.IsMatch(str, "^https://.+/MyTest$");

The ^ identifier matches the start of the string, while the $ identifier matches the end of the string. The .+ bit simply means any sequence of chars (except a null sequence).

You need to import the System.Text.RegularExpressions namespace for this, of course.

Noldorin
+2  A: 

In .NET:

^https://.*/MyTest$
Fiona Holder
A: 

HAndy tool for genrating regular expressions

http://txt2re.com/

Craig Angus
+1  A: 

Try Expresso, good for building .NET regexes and teaching you the syntax at the same time.

Adam Neal
+1 My current regex tool of choice.
Stevo3000
+4  A: 

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

Well, you could use regex for that. But it's clearer (and probably quicker) to just say what you mean:

str.StartsWith("https://") && str.EndsWith("/MyTest")

You then don't have to worry about whether any of the characters in your match strings need escaping in regex. (For this example, they don't.)

bobince
Yes! Excellent point.
Nicolas Webb