timmkrause
timmkrause

Reputation: 3621

How to match the whole string in RegEx?

I'm want to have two patterns:

1. "number/number number&chars"
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?

Upvotes: 0

Views: 7823

Answers (3)

Vitaly Zemlyansky
Vitaly Zemlyansky

Reputation: 331

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$

Upvotes: 2

ipr101
ipr101

Reputation: 24236

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

Upvotes: 2

robyaw
robyaw

Reputation: 2311

You need to use the start-of-line ^ and end-of-line $ characters; for example, for your second pattern, use ^\d_\d$.

Upvotes: 9

Related Questions