Need write # under each tweet C# - c#

Apologies in advance, English is not my first language.
I need to write under each tweet: #..... I am using Regex.IsMatch, but console write all tweets.
var tweet = tweets[i].Text;
var CreatedDate = tweets[i].CreatedDate.ToString("F");
var TweetTime = DateTime.Parse(CreatedDate);
var age = DateTime.Now.Subtract(TweetTime);
Console.WriteLine(tweet);
Console.WriteLine($"с момента создания прошло {age} времени");
Console.WriteLine();
var pattern = #"#\D*";
foreach(var sharp in tweet)
{
if (Regex.IsMatch(tweet, pattern, RegexOptions.IgnoreCase))
Console.WriteLine(sharp);
}

I don't know what you're trying to implement, but i see why your not getting the hashtag to print. Regex.IsMatch doesn't change the text it just evaluates it. Try something like this.
var pattern = #"#\D*";
foreach (var sharp in tweet)
{
var match = Regex.Match(pattern, sharp);
if (match.Success)
Console.WriteLine(Regex.Replace(sharp, match.Value, "#" + match.Value, RegexOptions.Singleline));
else
Console.WriteLine(sharp);
}

Thank's all
Right anwsers is next:
string pattern = #"\s*#(\w+)\s*";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(tweet);
if (matches.Count > 0)
{
foreach (Match match in matches)
Console.WriteLine(" " + match.Value);
}
Thanks for #M. Green

Related

C# RegEx to find values within a string

I am new to RegEx. I have a string like following. I want to get the values between [{# #}]
Ex: "Employee name is [{#John#}], works for [{#ABC Bank#}], [{#Houston#}]"
I would like to get the following values from the above string.
"John",
"ABC Bank",
"Houston"
Based on the solution Regular Expression Groups in C#.
You can try this:
string sentence = "Employee name is [{#john#}], works for [{#ABC BANK#}],
[{#Houston#}]";
string pattern = #"\[\{\#(.*?)\#\}\]";
foreach (Match match in Regex.Matches(sentence, pattern))
{
if (match.Success && match.Groups.Count > 0)
{
var text = match.Groups[1].Value;
Console.WriteLine(text);
}
}
Console.ReadLine();
Based on the solution and awesome breakdown for matching patterns inside wrapping patterns you could try:
\[\{\#(?<Text>(?:(?!\#\}\]).)*)\#\}\]
Where \[\{\# is your escaped opening sequence of [{# and \#\}\] is the escaped closing sequence of #}].
Your inner values are in the matching group named Text.
string strRegex = #"\[\{\#(?<Text>(?:(?!\#\}\]).)*)\#\}\]";
Regex myRegex = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline);
string strTargetString = #"Employee name is [{#John#}], works for [{#ABC Bank#}], [{#Houston#}]";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
var text = myMatch.Groups["Text"].Value;
// TODO: Do something with it.
}
}
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Test("the quick brown [{#fox#}] jumps over the lazy dog."));
Console.ReadLine();
}
public static string Test(string str)
{
if (string.IsNullOrEmpty(str))
return string.Empty;
var result = System.Text.RegularExpressions.Regex.Replace(str, #".*\[{#", string.Empty, RegexOptions.Singleline);
result = System.Text.RegularExpressions.Regex.Replace(result, #"\#}].*", string.Empty, RegexOptions.Singleline);
return result;
}
}
}

C# Regex extract certain digits from a number

I am trying to extract the digits from 10:131186; and get 10131186 without the : and ;.
What is the Regex pattern I need to create?
var input = "10:131186;";
string pattern = ":(.*);";
Match m = Regex.Match(input, pattern);
Console.WriteLine(m.Value);
With the above code, I am getting :131186; instead of 10121186.
Why you need to use Regex. It's slower than using string.Replace method
string input = "10:131186;";
input = input.Replace(":", "");
input = input.Replace(";", "");
Console.WriteLine(input);
You can try using Regex.Replace:
var input = "10:131186;";
string pattern = #"(\d+):(\d+);";
string res = Regex.Replace(input, pattern, "$1$2");
Console.WriteLine(res);
and you can also use Split with Join:
var input = "10:131186;";
Console.WriteLine(string.Join("", input.Split (new char[] { ':', ';' }, StringSplitOptions.RemoveEmptyEntries)));
Please try this..
string input = "10:131186;";
input = input.Replace(":", String.Empty).Replace(";", string.Empty);
Just print the group index 1.
var input = "10:131186;";
string pattern = ":(.*);";
Match m = Regex.Match(input, pattern);
Console.WriteLine(m.Value[1]);
or use assertions.
var input = "10:131186;";
string pattern = "(?<=:).*?(?=;)";
Match m = Regex.Match(input, pattern);
Console.WriteLine(m.Value);
You could use the pattern \\d+ to match digits in the string and concatenate them into a single string.
using System;
using System.Text;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string input = "10:131186;";
MatchCollection mCol = Regex.Matches(input, "\\d+");
StringBuilder sb = new StringBuilder();
foreach (Match m in mCol)
{
sb.Append(m.Value);
}
Console.WriteLine(sb);
}
}
Results:
10131186
Demo

How to check if a regex groups are equal?

I have a RegEx that checks my string. In my string I have two groups ?<key> and ?<value>. So here is my sample string:
string input = "key=value&key=value1&key=value2";
I use MatchCollections and when I try to print my groups on the console that here is my code:
string input = Console.ReadLine();
string pattern = #"(?<key>\w+)=(?<value>\w+)";
Regex rgx = new Regex(pattern);
MatchCollection matches = rgx.Matches(input);
foreach (Match item in matches)
{
Console.Write("{0}=[{1}]",item.Groups["key"], item.Groups["value"]);
}
I get an output like this: key=[value]key=[value1]key=[value2]
But I want my output to be like this: key=[value, value1, value2]
My point is how to check the group "key" if it's equal to the previous one so I can make the output like that I want.
You can use a Dictionary<string, List<string>>:
string pattern = #"(?<key>\w+)=(?<value>\w+)";
Regex rgx = new Regex(pattern);
MatchCollection matches = rgx.Matches(input);
Dictionary<string, List<string>> results = new Dictionary<string, List<string>>();
foreach (Match item in matches)
{
if (!results.ContainsKey(item.Groups["key"].Value)) {
results.Add(item.Groups["key"].Value, new List<string>());
}
results[item.Groups["key"].Value].Add(item.Groups["value"].Value);
}
foreach (var r in results) {
Console.Write("{0}=[{1}]", r.Key, string.Join(", ", r.Value));
}
Note the use of string.Join to output the data in the format required.
Use a Dictionary<string,List<string>>
Something like:
var dict = new Dictionary<string,List<string>>();
foreach (Match item in matches)
{
var key = item.Groups["key"];
var val = item.Groups["value"];
if (!dict.ContainsKey(key))
{
dict[key] = new List<string>();
}
dict[key].Add(val);
}
You can use Linq GroupBy method:
string input = "key=value&key=value1&key=value2&key1=value3&key1=value4";
string pattern = #"(?<key>\w+)=(?<value>\w+)";
Regex rgx = new Regex(pattern);
MatchCollection matches = rgx.Matches(input);
foreach (var result in matches
.Cast<Match>()
.GroupBy(k => k.Groups["key"].Value, v => v.Groups["value"].Value))
{
Console.WriteLine("{0}=[{1}]", result.Key, String.Join(",", result));
}
Output for snippet (here I've added another key key1 with two values into you original input string):
key=[value,value1,value2]
key1=[value3,value4]

Scrape Data and join fields from web in c#

I'm trying to make a simple TVchannel guide for a school project using C#.
I made this, viewing a youtube tutorial:
List<string> programasSPTV1 = new List<string>();
List<string> horasSPTV1 = new List<string>();
WebClient web = new WebClient();
String html = web.DownloadString("http://www.tv.sapo.pt/programacao/detalhe/sport-tv-1");
MatchCollection m1 = Regex.Matches(html, "\\s*(.+?)\\s*", RegexOptions.Singleline);
MatchCollection m2 = Regex.Matches(html, "<p>\\s*(.+?)\\s*</p>", RegexOptions.Singleline);
foreach(Match m in m1)
{
string programaSPTV1 = m.Groups[1].Value;
programasSPTV1.Add(programaSPTV1);
}
foreach (Match m in m2)
{
string hora_programaSPTV1 = m.Groups[1].Value;
horasSPTV1.Add(hora_programaSPTV1);
}
listBox1.DataSource = programasSPTV1 + horasSPTV1;
The last line is not correct... :(
What I really need is to get the time and program together in the same box...
Something like
17h45 : Benfica-FCPorto
And not 17h45 in a box and Benfica-FCPorto in another... :/
How can I do that?
Assuming that counts in both lists are the same, then the following should give you what you want:
listBox1.DataSource = programasSPTV1.Zip(horasSPTV1, (a,b) => (a + " : " + b)).ToList();

SplitString or SubString or?

Is there (.NET 3.5 and above) already a method to split a string like this:
string str = "{MyValue} something else {MyOtherValue}"
result: MyValue , MyOtherValue
Do like:
string regularExpressionPattern = #"\{(.*?)\}";
Regex re = new Regex(regularExpressionPattern);
foreach (Match m in re.Matches(inputText))
{
Console.WriteLine(m.Value);
}
System.Console.ReadLine();
dont forget to add new namespace: System.Text.RegularExpressions;
You can use regular expressions to do it. This fragment prints MyValue and MyOtherValue.
var r = new Regex("{([^}]*)}");
var str = "{MyValue} something else {MyOtherValue}";
foreach (Match g in r.Matches(str)) {
var s = g.Groups[1].ToString();
Console.WriteLine(s);
}
MatchCollection match = Regex.Matches(str, #"\{([A-Za-z0-9\-]+)\}", RegexOptions.IgnoreCase);
Console.WriteLine(match[0] + "," + match[1]);
Something like this:
string []result = "{MyValue} something else {MyOtherValue}".
Split(new char[]{'{','}'}, StringSplitOptions.RemoveEmptyEntries)
string myValue = result[0];
string myOtherValue = result[2];

Categories

Resources