-3

I'm looking for a way to find and extract the string matching a pattern in a string without a space :

string regexpattern = @"[A-Z]{4}\d{4}$";                    // ex : BERF4787            
string stringWithoutSpace = "stringsampleBERF4787withpattern";

string stringMatchPattern = ???         //I want to get BEFR4787 in this variable

1 Answers1

0

You are almost there. The problem in your pattern is the $ which matches the end of a string. Since in your example the "BERF4787" is located in the middle of the string you should simply remove it:

string regexpattern = @"[A-Z]{4}\d{4}";                    // ex : BERF4787            
string stringWithoutSpace = "stringsampleBERF4787withpattern";

If you want to match your pattern in a string you can use the Regex.Match method which returns an object of type Match. To get the matched value you need to use the Match.Value property like this:

string stringMatchPattern = Regex.Match(stringWithoutSpace, regexpattern).Value;
Mong Zhu
  • 20,890
  • 7
  • 33
  • 66