0
"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?

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

2 Comments

I don't know why it was downvoted. I upvote it, I think it was really clever!
This solutions breaks if the part before "TweetID" (is it some kind of title?) happens to contain a number.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.