user3344142
user3344142

Reputation: 31

C# regular expressions, beginning of the string

I would like to ask you a simple question about regular expressions:

How can I compare only the beginning of the string?

For example: Car [ 200 ; 200 ; 200 ], Bike [20]

if (item.Name == "Car*") { textBox.Text = "Car"; }

I don't know what I must type instead of "*" to make the rest of the string irrelevant.

Upvotes: 1

Views: 748

Answers (7)

IllusiveBrian
IllusiveBrian

Reputation: 3214

Although I would recommend using String.StartsWith as others have suggested, the regex you are looking for I believe is:

^[cC]ar

Assuming case insensitivity

Upvotes: 0

mnieto
mnieto

Reputation: 3874

if you still want to do with regular expression:

if (Regex.IsMatch(item.Name, "^Car")) {
    //Something to do
}

or, case insensitive:

if (Regex.IsMatch(item.Name, "^Car", RegexOptions.CultureInvariant)) {
    //Something to do
}

Or assign directly to the textbox:

Match m = Regex.Match(item.Name, "^(Car)(.*)");
if (m.Success)
    textBox.Text = m.Groups[1].Value;

Upvotes: 1

Nitesh Kumar SHARMA
Nitesh Kumar SHARMA

Reputation: 98

Ofcourse you should use String.StartWith() function If you use regex it will mess up your code . i mean it will take more time i think.

You can go like this.

if (item.Name.startsWith("Car")) { textBox.Text = "Car"; }

Upvotes: 0

tom.dietrich
tom.dietrich

Reputation: 8347

If you want to use regex, then you want (?i:^car.*)

  • (?i: : turns on case ignore for the rest for the rest of the group.
  • ^ : matches start of string.
  • car : looks for the string "car"
  • .* : matches anything else, any number of characters.
  • ) : ends the group

You could also remove the group stuff and use the ignore case option on the regex object itself.

Upvotes: 0

Hooch
Hooch

Reputation: 29673

There is no need for regex. There is nice method on String class calld StartsWith(string argument) MSDN: http://msdn.microsoft.com/pl-pl/library/system.string.startswith(v=vs.110).aspx

Use it like this:

string MyString = "Car [ 200 ; 200 ; 200 ], Bike [20]"
if(MyString.StartsWith("Car")) Do what you whant

Upvotes: 0

Selman Genç
Selman Genç

Reputation: 101681

I don't see a reason to use Regex here. you can use String.StartsWith

if(item.Name.StartsWith("Car")) { textBox.Text = "Car"; }

Upvotes: 7

Habib
Habib

Reputation: 223237

Instead of REGEX, you can do that with string.StartsWith

if(item.Name.StartsWith("Car"))

If you want case insensitive comparison then you can do :

if(item.Name.StartsWith("car",StringComparison.InvariantCultureIgnoreCase))

Upvotes: 4

Related Questions