0

I want to find out, whether my string contains a text like #1, #a, #abc, #123, #abc123dsds and so on... ('#' character with one or more characters (digits and letters).

My code so far won't work:

string test = "#123";
boolean matches = test.Contains("#.+");

The matches variable is false.

3
  • 8
    String.Contains does not accept a regex. Use Regex.IsMatch(test, "#.+"). Commented Jan 19, 2016 at 14:51
  • Is there a reason why you are using boolean instead of bool? Commented Jan 19, 2016 at 14:56
  • 2
    If you are after letters and digits explicetely, then you could use [A-Za-z0-9] instead of ., because as is you could simply use .startsWith("#") and .length > 1. Commented Jan 19, 2016 at 14:57

5 Answers 5

6

String.Contains does not accept a regex.

Use Regex.IsMatch:

var matches = Regex.IsMatch(test, "#.+");
Sign up to request clarification or add additional context in comments.

1 Comment

If you really need to check for letters and digits only, you can use @"#[\p{L}\d]+" pattern.
2

test.Contains("#.+"); does not "understand" regular expressions. It literally checks if the string test literally contains #.+ sequence of characters, which #123 does not contain.

Use Regex.IsMatch instead:

bool matches = Regex.IsMatch(test, "#.+");

Demo.

Comments

2

You need to use Regex in order to use a regex pattern.

string text = "#123";
Regex rgx = new Regex("#[a-zA-Z0-9]+");
var match = rgx.Match(text);
bool matche = match.Success)

Comments

2

Or without regex, you can use a combination of StartsWith, Enumerable.Any and char.IsLetterOrDigit methods like;

var s = "#abc123dsds+";
var matches = s.Length > 1 && s.StartsWith("#") && s.Substring(1).All(char.IsLetterOrDigit);

7 Comments

Why is regex better than s.StartsWith("#") && s.Substring(1).All(Char.IsLetterOrDigit)? However, currently it also accepts # as valid.
@TimSchmelter Just my opinion because it is more simpler than my solution. And as you said, ## or ### are does not match in my answer.
@TimSchmelter Wait a second, it shouldn't match because # is not a letter of course. I delete that sentences. My answer is better. HAHA :)
But it still allows "#" as match even if # should be followed by a letter or digit. So a Length > 1 is required. It's subjective but imo string methods are simpler.
@TimSchmelter Right. I think ?: solve this. Updated.
|
0

Well this worked for me. \# checks if it starts with #, \w checks if it is a word.

 class Program
{
    static void Main(string[] args)
    {
        string text = "#2";
        string pat = @"\#(\w+)";

        Regex r = new Regex(pat);

        Match m = r.Match(text);

        Console.WriteLine(m.Success);
        Console.ReadKey();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.