I’m looking for a way to decide if a single regular expression matches a whole string, start of the string, or a part of it in C#.
In Java, you can construct a Matcher object, and use the methods matches() to check if it is a match for the whole input, lookingAt() to see if it matches the start of the input, and find() to see if there is any match from within the strung at all.
In .NET, I can use Match.Success to see if there is any match, and check Match.Index and Match.Length for the above conditions.
The problem is, it does not try to match the whole input if a smaller match is found. For example, if the input “1234” is presented to the Regex @"\d{2}|\d{4}", it will match the first two digits.
In such a case, I need to have another Regex constructed with the pattern @"^(\d{2}|\d{4})$" to test for the whole input, and then test the other one to see if it matches the beginning.
Isn’t there a way to tell the same Regex class to prefer whole-input matches, so that I won’t need to create (and compile) another Regex for this reason?
EDIT: The question is not about the pattern, it is just an example to show what I mean.
No, there is no “only match at the beginning” or “only match the entire string” regex method in .NET. You do need to construct this behaviour using anchors.
In a way, I much prefer this over what Java does for two reasons:
.matches()because they don’t know it has to match the entire string. I’ve seen at least a dozen questions on SO about this exact problem.re.search()vs.re.match()*).That said, it’s also very easy to do:
@"\A(?:"+ original regex +")"–>lookingAt()(now who thought of that name)?@"\A(?:"+ original regex +@")\z"–>matches()*
re.match()behaves like Java’slookingAt(), not likematches(), in case you were wondering.