demon13
demon13

Reputation: 11

Extract serial number from string by using regex in c#

Serial Number :- 4540107708_E4-UR730RSQ_XICM_1

Code (C#):-

string Pattern = "^[0-9]{1,10}_[a-z0-9A-Z-]{2,12}_XICM_[0-9]$";

string inputStr = "Abcd Abcdefg Abcdefghij xyzyzxue, 4540107708_E4-UR730RSQ_XICM_1 abcdefg Abcd Abcdefg Abcdefghij xyzyzxue."; 

Regex regex = new Regex(Pattern,RegexOptions.None);

Match match = regex.Match(inputStr);

if (match.Success)
{
   string matchValue = match.Value;
   Console.WriteLine(matchValue);
   Console.WriteLine(match.Value);
   Console.ReadLine();
}

i want this serial number (4540107708_E4-UR730RSQ_XICM_1) from inputStr.

please help..

output

Upvotes: 0

Views: 380

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626802

The ^ anchor requires the match to appear at the start of the string and $ requires the match to appear at the end of the string. What you need is to find the match as a whole word. Use word boundaries:

\b[0-9]{1,10}_[a-z0-9A-Z-]{2,12}_XICM_[0-9]\b
^^                                         ^^

See the regex demo

Upvotes: 1

Related Questions