Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple C# regex question

Tags:

c#

regex

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).

like image 625
Rasto Avatar asked Dec 05 '22 02:12

Rasto


2 Answers

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.

like image 139
Mark Byers Avatar answered Dec 19 '22 12:12

Mark Byers


use an anchored pattern

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

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

like image 25
knittl Avatar answered Dec 19 '22 13:12

knittl