How to get the port number alone using regex in c#?

83 views Asked by At

can anyone pls guide me to get the port number alone from the below line? Note: i have maintain this whole line as string.

"C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\11.0\WebDev.WebServer40.EXE" /port:4274 /path:"F:\Program Files (x86)\Samples\test\" /vpath:"/"

Output i expected is 4274 alone.

I have tried many solutions from stackoverflow. nothing helps.

Thanks in Advance.

Regards, Karthi

2

There are 2 answers

1
Avinash Raj On

You could simply use the below regex to get the number which exists next to the port: substring.

@"(?<=\bport\s*:\s*)\d+"
0
Wiktor Stribiżew On

You can use C# code without regex to obtain the number:

var val = string.Empty;
var port_num = inpt.Split(' ').
     Where(p => p.StartsWith("/port:")).FirstOrDefault();
if (!string.IsNullOrEmpty(port_num))
     val = port_num.Substring(port_num.IndexOf(':')+1);

Output:

enter image description here