I have a string ---TIMESTAMP Tue, 24 Oct 2017 02:11:56 -0400 [1508825516987]---
I want to get the value within the []
(i.e. 1508825516987
)
How can I get the value using Regex?
I have a string ---TIMESTAMP Tue, 24 Oct 2017 02:11:56 -0400 [1508825516987]---
I want to get the value within the []
(i.e. 1508825516987
)
How can I get the value using Regex?
Explanation:
\[
: [
is a meta char and needs to be escaped if you want to match it literally.(.*?)
: match everything in a non-greedy way and capture it.\]
: ]
is a meta char and needs to be escaped if you want to match it literally.Source of explanation: Click
static void Main(string[] args)
{
string txt = "---TIMESTAMP Tue, 24 Oct 2017 02:11:56 -0400 [1508825516987]---";
Regex regex = new Regex(@"\[(.*?)\]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match match = regex.Match(txt);
if (match.Success)
{
for (int i = 1; i < match.Groups.Count; i++)
{
String extract = match.Groups[i].ToString();
Console.Write(extract.ToString());
}
}
Console.ReadLine();
}
Links to learn to create regular expressions:
Update 1:
Regex regex = new Regex(@"^---.*\[(.*?)\]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
You can use the following code to get the outcome what you want!
MatchCollection matches = Regex.Matches("---TIMESTAMP Tue, 24 Oct 2017 02:11:56 -0400 [1508825516987]---", @"\[(.*?)\]", RegexOptions.Singleline);
Match mat = matches[0];
string val = mat.Groups[1].Value.ToString();
whereas the string val will contain the value what you required.