我想知道,我的字符串是否包含#1,#a,#abc,#123,#abc123dsds等文本...('#'字符包含一个或多个字符(数字和字母) )。
到目前为止,我的代码无效:
string test = "#123";
boolean matches = test.Contains("#.+");
matches
变量为false
。
答案 0 :(得分:6)
答案 1 :(得分:2)
test.Contains("#.+");
不理解"常用表达。它字面上检查字符串test
字面上是否包含#.+
字符序列,#123
不包含。
改为使用Regex.IsMatch
:
bool matches = Regex.IsMatch(test, "#.+");
答案 2 :(得分:2)
或者,如果没有正则表达式,您可以使用StartsWith
,Enumerable.Any
和char.IsLetterOrDigit
等方法的组合;
var s = "#abc123dsds+";
var matches = s.Length > 1 && s.StartsWith("#") && s.Substring(1).All(char.IsLetterOrDigit);
答案 3 :(得分:1)
您需要使用正则表达式才能使用正则表达式模式。
string text = "#123";
Regex rgx = new Regex("#[a-zA-Z0-9]+");
var match = rgx.Match(text);
bool matche = match.Success)
答案 4 :(得分:0)
这对我有用。 \#检查它是否以#开头,\ w检查它是否为单词。
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();
}
}