RegEx get highlited text C# - c#

i'am trying to get from this text:
updateServer
cInterface_test-184
cServer_test-184
dControl_test-178
mcontrol_doorinterface_test-178
the italic strings. Eg in second line test-184 i'am using the following regEx:
test+.*
But how can i extract the test-184 in a string in c# wpf ?
Thanks :)
EDIT: The Stars are not in the Text, I wanted to highlight the text i want

After 'test-', is there always a number?
If so, the following is the best for you:
static void Main(string[] args)
{
var text = #"
updateServer
cInterface_*test-184*
cServer_*test-184*
dControl_*test-178*
mcontrol_doorinterface_*test-178*
";
var pattern = #"test-\d*";
foreach (Match match in Regex.Matches(text, pattern))
Console.WriteLine(match);
}
If 'test-' is not a constant, you can use the following code:
static void Main(string[] args)
{
var text = #"
updateServer
cInterface_*test-184*cServer_*test-184*
cServer_*test-184*
dControl_*test-178*
mcontrol_doorinterface_*test-178*
";
var pattern = #"\*(.*?)\*";
foreach (Match match in Regex.Matches(text, pattern))
Console.WriteLine(match.Groups[1].Value);
}

You could use code llke this:
class Program
{
static void Main(string[] args)
{
var text = #"
updateServer
cInterface_*test-184*
cServer_*test-184*
dControl_*test-178*
mcontrol_doorinterface_*test-178*
";
foreach (Match match in Regex.Matches(text, "\\*(.*)\\*"))
{
Console.WriteLine(match.Groups[1].Value);
}
}
}

Related

Need write # under each tweet 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

How to extract a substring from one delimiter to another in C#?

My input is going to be as follows:
abc#gmail.com,def#yahoo.com;xyz#gmail.com;ghi#hotmail.com and so on
Now I want my output to be:
abc
def
xyz
ghi
The following is my code:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main(string[] args)
{
string str;
string[] newstr,newstr2;
Console.WriteLine("Enter the email addresses: ");
str=Console.ReadLine();
newstr=Regex.Split(str,",|;|#");
foreach (string s in newstr)
{
Console.WriteLine(s);
}
}
}
My output right now is:
abc
gmail.com
def
yahoo.com
xyz
gmail.com
ghi
hotmail.com
Any kind of help would be greatly appreciated. Thanks.
You shouldn't use regex for split, and should no split by #. Instead, use the follopwing code:
using System;
public class Program
{
public static void Main(string[] args)
{
string str;
string[] newstr;
Console.WriteLine("Enter the email addresses: ");
str = Console.ReadLine();
newstr = str.Split(new char[] { ',', ';' }); // Split to get a temporal array of addresses
foreach (string s in newstr)
{
Console.WriteLine(s.Substring(0, s.IndexOf('#'))); // Extract the sender from the email addresses
}
}
}
Edit:
Or, with LINQ:
using System;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
string str;
string[] newstr;
Console.WriteLine("Enter the email addresses: ");
str = Console.ReadLine();
newstr = str.Split(new char[] { ',', ';' }) // Split to get a array of addresses to work with
.Select(s => s.Substring(0, s.IndexOf('#'))).ToArray(); // Extract the sender from the email addresses
foreach (string s in newstr)
{
Console.WriteLine(s);
}
}
}
another approach without RegEx
string input = "abc#gmail.com,def#yahoo.com;xy#gmail.com; ghi#hotmail.com";
var result = input.Split(',', ';').Select(x => x.Split('#').First());
first Split the adresses by , and ;, then select the part before the # by splitting again.
You can use this email regex:
var regex = new Regex(#"(?<name>\w+([-+.']\w+)*)#\w+([-.]\w+)*\.\w+([-.]\w+)*");
var results =
regex.Matches("abc#gmail.com,def#yahoo.com;xyz#gmail.com;ghi#hotmail.com")
.Cast<Match>()
.Select(m => m.Groups["name"].Value)
.ToList();
Perhaps using this might help
str.Substring(0, str.LastIndexOf(" ")<0?0:str.LastIndexOf(" "));
As Mail is a weird thing with a complexe definition, I will never assume that something with an # is a mail.
My best try would be to convert the string to a MailAddress, just in case it look like a mail but it's not one because of some invalid char etc.
string input = "abc#gmail.com,ghi#hotmail.com;notme; #op this is not a mail!";
var result = input
.Split(',', ';') // Split
.Select(x =>
{
string adr = "";
try
{ // Create an MailAddress, MailAddress has no TryParse.
adr = new MailAddress(x).User;
}
catch
{
return new { isValid = false, mail = adr };
}
return new { isValid = true, mail = adr };
})
.Where(x => x.isValid)
.Select(x => x.mail);
Actually, in the regular expression, to capture some substring, you need to wrap the expected content by ( and )
Below code should work
string str22 = "abc#gmail.com;def#yahoo.com,xyz#gmail.com;fah#yao.com,h347.2162#yahoo.com.hk";// ghi#hotmail.com";
List<string> ret = new List<string>();
string regExp = #"(.*?)#.*?[,;]{1}|(.*)#";
MatchCollection matches = Regex.Matches(str22, regExp, RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
if (match.Success)
{
int pvt = 1;
while (string.IsNullOrEmpty(match.Groups[pvt].Value))
{
pvt++;
}
MessageBox.Show(match.Groups[pvt].Value);
}
}
return;
The regular expression is as below
(.*?)#.*?[,;]{1}|(.*)#
(.*?)#.*?[,;]{1} is fetching the substring before # and ? restrict it fetches the first match.
The last email do not contain , or ;, thus add a OR condition and fetch the last email name by the substring before #

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

Looping through Regex Matches

This is my source string:
<box><3>
<table><1>
<chair><8>
This is my Regex Patern:
<(?<item>\w+?)><(?<count>\d+?)>
This is my Item class
class Item
{
string Name;
int count;
//(...)
}
This is my Item Collection;
List<Item> OrderList = new List(Item);
I want to populate that list with Item's based on source string.
This is my function. It's not working.
Regex ItemRegex = new Regex(#"<(?<item>\w+?)><(?<count>\d+?)>", RegexOptions.Compiled);
foreach (Match ItemMatch in ItemRegex.Matches(sourceString))
{
Item temp = new Item(ItemMatch.Groups["item"].ToString(), int.Parse(ItemMatch.Groups["count"].ToString()));
OrderList.Add(temp);
}
Threre might be some small mistakes like missing letter it this example because this is easier version of what I have in my app.
The problem is that In the end I have only one Item in OrderList.
UPDATE
I got it working.
Thans for help.
class Program
{
static void Main(string[] args)
{
string sourceString = #"<box><3>
<table><1>
<chair><8>";
Regex ItemRegex = new Regex(#"<(?<item>\w+?)><(?<count>\d+?)>", RegexOptions.Compiled);
foreach (Match ItemMatch in ItemRegex.Matches(sourceString))
{
Console.WriteLine(ItemMatch);
}
Console.ReadLine();
}
}
Returns 3 matches for me. Your problem must be elsewhere.
For future reference I want to document the above code converted to using a declarative approach as a LinqPad code snippet:
var sourceString = #"<box><3>
<table><1>
<chair><8>";
var count = 0;
var ItemRegex = new Regex(#"<(?<item>[^>]+)><(?<count>[^>]*)>", RegexOptions.Compiled);
var OrderList = ItemRegex.Matches(sourceString)
.Cast<Match>()
.Select(m => new
{
Name = m.Groups["item"].ToString(),
Count = int.TryParse(m.Groups["count"].ToString(), out count) ? count : 0,
})
.ToList();
OrderList.Dump();
With output:

Categories

Resources