C# Find a matching string by regex

后端 未结 5 1764
有刺的猬
有刺的猬 2020-12-07 06:02

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).

相关标签:
5条回答
  • 2020-12-07 06:12

    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.

    0 讨论(0)
  • 2020-12-07 06:14

    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);
    
    0 讨论(0)
  • 2020-12-07 06:16

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-07 06:23

    String.Contains does not accept a regex.

    Use Regex.IsMatch:

    var matches = Regex.IsMatch(test, "#.+");
    
    0 讨论(0)
  • 2020-12-07 06:25

    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)
    
    0 讨论(0)
提交回复
热议问题