开发者

How to check if a Regex expression matches an entire string in c#?

开发者 https://www.devze.com 2022-12-16 02:41 出处:网络
I am new to regex expressions so sorry if this is a really noob question. I have a regex expression... What I want to do is check if a string matches the regex expression in its entirety without the

I am new to regex expressions so sorry if this is a really noob question.

I have a regex expression... What I want to do is check if a string matches the regex expression in its entirety without the regex expression matching any subsets of the string.

For example...

If my regex expression is looking for a match of \sA\s*, it should return a match if the string it is comparing it to is " A " but if it compares to the string " A B" it should not return 开发者_StackOverflowa match.

Any help would be appreciated? I code in C#.


You would normally use the start end end anchors ^ and $ respecitvely:

^\s*A*\s*$

Keep in mind that, if you regex engine supports multi-line, this may also capture strings that span multiple lines as long as one of those lines matches the regex(since ^ then anchors after any newline or string-start and $ before any newline or string end). If you're only running the regex against a single line, that won't be a problem.

If you want to ensure that a multi-line input is only a single line consisting of your pattern, you can use \A and \Z if supported - these mean start and end of string regardless of newlines.


If you cannot or don't want to change the regular expression, then you can also use:

var match = regex.Match(pattern);
if (match.Success && match.Length == pattern.Length)
{
    // TODO: Entire string was matched, and not a sub string
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号