tags:

views:

87

answers:

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  A: 

use an anchored pattern

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

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

knittl
+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.
Tomalak
A slight difference is that `.` doesn't match `"\n"` unless you specify `RegexOptions.Singleline`. Not too important, really `:P`
Kobi
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
Mark Byers is right of cause. Please read the "Edit" paragraph I added right now. Thanks for answers.
drasto
+3  A: 

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

^.$
Tomalak
+1 Thanks, This is simple and clear answer.
drasto
+5  A: 

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.

Mark Byers
This answer is the most complex one, I consider question fully answered by this one.
drasto
+4  A: 
"b".Length == 1

is a much better candidate than

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