How to match the whole string in RegEx?
I'm want to have two patterns:
1. "number/number number&ch开发者_开发技巧ars"
2. "number_number"
1. "\d/\d \s"
2. "\d_\d"
These don't really work. For example the second one also matches "asdf894343_84939". How do I force the pattern to match the WHOLE string?
You need to use the start-of-line ^
and end-of-line $
characters; for example, for your second pattern, use ^\d_\d$
.
For second task(number_number) you can use [^a-zA-Z]\d.*_\d.*, in you example asdf894343_84939, you get 894343_84939, or if you want to get only one digit - remove .* after \d.
In your first task, you also may use \d.*/\d[^\s], for example, if you have 34/45 sss - you get 34/45. If you want to get result from whole string you must use in you pattern: ^your pattern$
You colud use the '\A' and '\Z' flags -
Regex.IsMatch(subjectString, @"\A\d_\d\Z");
\A Matches the position before the first character in a string. Not affected by the MultiLine setting
\Z Matches the position after the last character of a string. Not affected by the MultiLine setting.
From - http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet
精彩评论