4

Question: What's the simplest way how to test if given Regex matches whole string ?

An example: E.g. given Regex re = new Regex("."); I want to test if given input string has only one character using this Regex re. How do I do that ?

In other words: I'm looking for method of class Regex that works similar to method matches() in class Matcher in Java ("Attempts to match the entire region against the pattern.").

Edit: This question is not about getting length of some string. The question is how to match whole strings with regular exprestions. The example used here is only for demonstration purposes (normally everybody would check the Length property to recognise one character strings).

4 Answers 4

5

If you are allowed to change the regular expression you should surround it by ^( ... )$. You can do this at runtime as follows:

string newRe = new Regex("^(" + re.ToString() + ")$");

The parentheses here are necessary to prevent creating a regular expression like ^a|ab$ which will not do what you want. This regular expression matches any string starting with a or any string ending in ab.


If you don't want to change the regular expression you can check Match.Value.Length == input.Length. This is the method that is used in ASP.NET regular expression validators. See my answer here for a fuller explanation.

Note this method can cause some curious issues that you should be aware of. The regular expression "a|ab" will match the string 'ab' but the value of the match will only be "a". So even though this regular expression could have matched the whole string, it did not. There is a warning about this in the documentation.

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

1 Comment

This answer is the most complex one, I consider question fully answered by this one.
4

use an anchored pattern

Regex re = new Regex("^.$");

for testing string length i'd check the .Length property though (str.Length == 1) …

4 Comments

+1 for the obvious "check string length" approach. Unless you want to match for a certain character according to a more complex rule, that's the best approach by far.
A slight difference is that . doesn't match "\n" unless you specify RegexOptions.Singleline. Not too important, really :P
The obvious check is fine but I suspect though that it was just an example to clarify the question... not actually what he wants to do.
Mark Byers is right of cause. Please read the "Edit" paragraph I added right now. Thanks for answers.
4
"b".Length == 1

is a much better candidate than

Regex.IsMatch("b", "^.$")

Comments

3

You add "start-of-string" and "end-of-string" anchors

^.$

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.