A simple question with C # regex

Question : What is the easiest way to check if the given Regex matches the entire string?

Example: For example. given Regex re = new Regex("."); I want to test if the given input line contains only one character using this Regex re . How to do it?

In other words : I am looking for a method of the Regex class that works similarly to the matches() method in the Matcher class in Java ("Attempts to match the entire area against the template.").

Edit: This question is not about the length of multiple string . The question is how to match integer strings with regular expressions. The example used here is for demonstration purposes only (usually everyone would check the Length property to recognize one character string).

+4
source share
4 answers

If you are allowed to modify the regular expression, you must surround it with ^( ... )$ . You can do this at runtime as follows:

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

Brackets are needed here to prevent the creation of a regular expression such as ^a|ab$ that will not do what you want. This regular expression matches any line starting with a or any line ending with ab .


If you do not want to change the regex, you can check Match.Value.Length == input.Length . This is the method used in ASP.NET regex validators. See my answer here for a more complete explanation.

Please note that this method may cause some interesting problems that you should be aware of. The regular expression "a | ab" will match the string "ab", but the match value will only be "a". Therefore, although this regular expression could match the entire string, it is not. The documentation has a warning about this.

+5
source

use anchored pattern

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

to check the length of the string I would check the .Length property though ( str.Length == 1 ) ...

+4
source
 "b".Length == 1 

- a much better candidate than

 Regex.IsMatch("b", "^.$") 
+4
source

You add the beginning of line and end of line anchor

 ^.$ 
+3
source

All Articles