caesay
caesay

Reputation: 17213

matching string in C#

Alright, so i need to be able to match strings in ways that give me more flexibility. so, here is an example. for instance, if i had the string "This is my random string", i would want some way to make

" *random str* ",
" *is __ ran* ", 
" *is* ", 
" *this is * string ",

all match up with it, i think at this point a simple true or false would be okay to weather it match's or not, but id like basically * to be any length of any characters, also that _ would match any one character. i can't think of a way, although im sure there is, so if possible, could answers please contain code examples, and thanks in advance!

Upvotes: 2

Views: 229

Answers (2)

Peter Boughton
Peter Boughton

Reputation: 112160

I can't quite figure out what you're trying to do, but in response to:

but id like basically * to be any length of any characters, also that _ would match any one character

In regex, you can use . to match any single character and .+ to match any number of characters (at least one), or .* to match any number of characters (or none if necessary).

So your *is __ ran* example might turn into the regex .+is .. ran.+, whilst this is * string could be this is .+ string.

If this doesn't answer your question then you might want to try re-wording it to make it clearer.

For learning more regex syntax, a popular site is regular-expressions.info, which provides pretty much everything you need to get started.

Upvotes: 5

SLaks
SLaks

Reputation: 887453

Use Regular Expressions.

In C#, you would use the Regex class.

For example:

var str = "This is my random string";

Console.WriteLine(Regex.IsMatch(str, ".*is .. ran.*"));    //Prints "True"

Upvotes: 3

Related Questions