mmarques
mmarques

Reputation: 655

Regular expression to match exactly the start of a string

I'm trying to build a regular expression in c# to check whether a string follow a specific format.

The format i want is: [digit][white space][dot][letters]

For example:

123 .abc follow the format

12345 .def follow the format

123 abc does not follow the format

I write this expression but it not works completelly well

Regex.IsMatch(exampleString, @"^\d+ .")

Upvotes: 1

Views: 261

Answers (3)

Jerry
Jerry

Reputation: 71538

^ matches the start of the string, and you got it right.

\d+ matches one or more digits, and you got that one right as well.

A space in a regex matches a literal space, so that works too!

However, a . is a wildcard and will match any one character. You will need to escape it with a backslash like this if you want to match a literal period: \..

To match letters now, you can use [a-z]+ right after the period.

@"^\d+ \.[a-z]+"

Upvotes: 6

Tyllyn
Tyllyn

Reputation: 289

For you to get yours to match, keep in mind that the period in regular expressions is a special character that will match any character, so you'll need to escape that.

In addition, \s is a match for any white-space character (tabs, line breaks).

^\d+\s+ \..+

(untested)

Upvotes: 0

Douglas
Douglas

Reputation: 54877

The dot is a special character in regex, which matches any character (except, typically, newlines). To match a literal ., you need to escape it:

Regex.IsMatch(exampleString, @"^\d+ \.")

If you want to include the condition for the succeeding letters, use:

Regex.IsMatch(exampleString, @"^\d+ \.[A-Za-z]+$")

Upvotes: 2

Related Questions