简体   繁体   中英

Regex in C# Console App

"Fire hose Tweet - TweetID: 436660665219305472 - ActorID: 120706813"

"Fire hose Tweet - TweetID: 436660665219305472"

"Fire hose Tweet - TweetID: 436660665219305472 "

I am new in regex C# what will be regex to extract tweet Id 436660665219305472 from sample string 1 & string 2?

You don't need regex, you can use Split method and LINQ to get what you want :

var input = "Fire hose Tweet - TweetID: 436660665219305472 - ActorID: 120706813";

var output = input.Split().First(x => x.All(char.IsDigit));

Take a look at the named grouping construct for .NET

Here's an example that matches your scenario.

string str1 = "Fire hose Tweet - TweetID: 436660665219305472 - ActorID: 120706813";

string str2 = "Fire hose Tweet - TweetID: 436660665219305472";

var tweetIdRegex = new Regex(@"TweetID:\s(?<TweetID>\d+)", RegexOptions.ExplicitCapture | RegexOptions.Compiled);

Console.WriteLine(tweetIdRegex.Match(str1).Value);
Console.WriteLine(tweetIdRegex.Match(str2).Value);

Output:

TweetID: 436660665219305472
TweetID: 436660665219305472

Alternatively, if you end up with a regular expression that represents the entire string, and you're using grouping constructs, you could do the following, which is why I mentioned named grouping constructs. This is a technique I've used extensively.

GroupCollection tweetInfo = tweetIdRegex.Match(str1).Groups;
Console.WriteLine(tweetInfo["TweetID"].Value);

in which case it would output:

436660665219305472

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM