问题
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?
回答1:
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.
回答2:
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.
回答3:
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.)
回答4:
In .NET:
^https://.*/MyTest$
回答5:
Try Expresso, good for building .NET regexes and teaching you the syntax at the same time.
回答6:
HAndy tool for genrating regular expressions
http://txt2re.com/
来源:https://stackoverflow.com/questions/1404669/how-to-check-if-a-string-starts-and-ends-with-specific-strings