C# 在没有空格的字符串中查找模式
我正在寻找一种方法,在没有空格的字符串中查找并提取与模式匹配的字符串:C# 在没有空格的字符串中查找模式,c#,.net,regex,string,C#,.net,Regex,String,我正在寻找一种方法,在没有空格的字符串中查找并提取与模式匹配的字符串: string regexpattern = @"[A-Z]{4}\d{4}$"; // ex : BERF4787 string stringWithoutSpace = "stringsampleBERF4787withpattern"; string stringMatchPattern = ??? //I want to get BEFR4
string regexpattern = @"[A-Z]{4}\d{4}$"; // ex : BERF4787
string stringWithoutSpace = "stringsampleBERF4787withpattern";
string stringMatchPattern = ??? //I want to get BEFR4787 in this variable
你就快到了。模式中的问题是匹配字符串结尾的
$
。因为在您的例子中,<代码>“BEF47 47”<代码>位于字符串的中间,您应该简单地删除它:
string regexpattern = @"[A-Z]{4}\d{4}"; // ex : BERF4787
string stringWithoutSpace = "stringsampleBERF4787withpattern";
如果要在字符串中匹配模式,可以使用返回类型为的对象的方法。
要获得匹配的值,需要使用如下属性:
string stringMatchPattern = Regex.Match(stringWithoutSpace, regexpattern).Value;