Find each RegEx match in string - c#

id like to do something like
foreach (Match match in regex)
{
MessageBox.Show(match.ToString());
}
Thanks for any help...!

There is a RegEx.Matches method:
foreach (Match match in regex.Matches(myStringToMatch))
{
MessageBox.Show(match.Value);
}
To get the matched substring, use the Match.Value property, as shown above.

from MSDN
string pattern = #"\b\w+es\b";
Regex rgx = new Regex(pattern);
string sentence = "Who writes these notes?";
foreach (Match match in rgx.Matches(sentence))
{
Console.WriteLine("Found '{0}' at position {1}",
match.Value, match.Index);
}

You first need to declare the string to be analyzed, and then the regex pattern.
Finally in the loop you have to instance regex.Matches(stringvar)
string stringvar = "dgdfgdfgdf7hfdhfgh9fghf";
Regex regex = new Regex(#"\d+");
foreach (Match match in regex.Matches(stringvar))
{
MessageBox.Show(match.Value.ToString());
}

Related

Get the Number from a string

I want to trim a string and get the number between special characters.
For example there is a string BC/PO/88/2018 from it i want to get 88.
you can make use of regular expression and extract number
Match match = Regex.Match("BC/PO/88/2018 f" , #"(\d+)");
if (match.Success) {
return int.Parse(match.Groups[0].Value);
}
other way is you can do with the help of String.Split as suggested in comments if you are sure about string coming as input i.e. sure about format of string.
You could use Regular Expressions:
string strRegex = #"[A-Z]{2}/[A-Z]{2}/(?<MyNumber>[0-9]*)/[0-9]{4}";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = #"BC/PO/88/2018";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}

Problems with regex in c# only returning a single match

I'm building a regex and I'm missing something as it's not working properly.
my regex logic is trying to look for anything that has #anychars# and return the number of matches on the sentence and not a single match.
Here are a few examples
1- #_Title_# and #_Content_# should return two matches: #_Title_# and #_Content_#.
2- Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_# should return 3 matches: #_TemplateName_# #_Full_Product_Name_# and #_Short_Description_#
and so on. Here is what my regex looks like: ^(.*#_.*_#.*)+$
any thoughts on what I'm doing wrong?
Something as simple as:
#.*?#
Or:
#_.*?_#
If you are trying to match the underscores too (it wasn't clear in the original version of the question). Or:
#_(.*?)_#
Which makes it easier to extract the token between your #_ and _# delimiters as a group.
Should work. The *? is key. It's non-greedy. Otherwise you match everything between the first and last #
So for example:
var str = "Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_#";
var r = new Regex("#_(.*?)_#");
foreach (Match m in r.Matches(str))
{
Console.WriteLine(m.Value + "\t" + m.Groups[1].Value);
}
Outputs:
#_TemplateName_#     TemplateName
#_Full_Product_Name_#    Full_Product_Name
#_Short_Description_#    Short_Description
Try this :
string[] inputs = {
"#Title# and #Content#",
"Product #TemplateName# #_Full_Product_Name_# more text. text text #_Short_Description_#"
};
string pattern = "(?'string'#[^#]+#)";
foreach (string input in inputs)
{
MatchCollection matches = Regex.Matches(input, pattern);
Console.WriteLine(string.Join(",",matches.Cast<Match>().Select(x => x.Groups["string"].Value).ToArray()));
}
Console.ReadLine();
You regular expression is not correct. In addition, you want to loop through match if you want all matching.
static void Main(string[] args)
{
string input = "Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_#",
pattern = "#_[a-zA-Z_]*_#";
Match match = Regex.Match(input, pattern);
while (match.Success)
{
Console.WriteLine(match.Value);
match = match.NextMatch();
}
Console.ReadLine();
}
Result
Don't use anchors and change your regex to:
(#[^#]+#)
In regex the [^#] expression means any character BUT #
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = #"(#[^#]+#)";
Regex rgx = new Regex(pattern);
string sentence = "#blah blah# asdfasdfaf #somethingelse#";
foreach (Match match in rgx.Matches(sentence))
Console.WriteLine("Found '{0}' at position {1}",
match.Value, match.Index);
}
}

C# Regex is matching too much

My regex should work like this: https://regex101.com/r/dY9jI4/1
It should Match only Nicknames (personaname).
My C# code looks like this:
string pattern = #"personaname"":\s+""([^""]+)""";
string users = webClient.DownloadString("http://pastebin.com/raw/cDHTXXD3");
Regex regex = new Regex(pattern);
MatchCollection matches = regex.Matches(users);
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
But in VS15 my regex in matching my whole pattern, so console output looks like:
personaname": "Tom"
personaname": "Emily"
Is something wrong with my pattern? How can I fix it?
So while the actual answer would be to just parse this JSON and get the data, your problem is in Match, you need match.Groups[1].Value to get that unnamed group.
string pattern = #"personaname"":\s+""(?<name>[^""]+)""";
string users = webClient.DownloadString("http://pastebin.com/raw/cDHTXXD3");
Regex regex = new Regex(pattern);
MatchCollection matches = regex.Matches(users);
foreach (Match match in matches)
{
Console.WriteLine(match.Groups["name"].Value);
}

Regex replace specific words in c#

I have a string like "Please .... {##url} something{##test}somethinng ... some{##url} ....", would like to replace exactly the strings {##url} and {##test} through regex in c#
Kindly help me to get the regex pattern
Thanks in advance!
Regex to get string between curly braces "{I want what's between the curly braces}"
https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex(v=vs.110).aspx
So something like
string pattern = #"/{(.*?)}/";
string input = "Please .... {##url} something{##test}somethinng ... some{##url} ....";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(input);
if (matches.Count > 0)
{
Console.WriteLine("{0} ({1} matches):", input, matches.Count);
foreach (Match match in matches)
input = input.replace(match.value, "");
}

Regex to parse string input

I want to use regex to parse it into groups
string input = #"(1,2)(3,4)";
Regex.Matches(input, #"\((\d,\d)\)");
The results I get is not only 1,2 and 3,4 but also spaces. Can you guys help me ?
EDIT:
I want to get 2 groups 1,2 and 3,4.
string input = #"(1,2)(3,4)";
MatchCollection inputMatch= Regex.Matches(collegeRecord.ToString(), #"(?<=\().*?(?=\))");
For current string you will get two outputs:
inputMatch[0].Groups[0].Value;
inputMatch[0].Groups[1].Value;
Or
You can also try foreach loop
foreach (Match match in inputMatch)
{
}
I have not tested this code,
My Working Example:
MatchCollection facilities = Regex.Matches(collegeRecord.ToString(), #"<td width=""38"">(.*?)image_tooltip");
foreach (Match facility in facilities)
{
collegeDetailDH.InsertFacilityDetails(collegeDetailDH._CollegeID, facility.ToString().Replace("<td width=\"38\">", string.Empty).Replace("<span class=\"icon_", string.Empty).Replace("image_tooltip", string.Empty));
}
How do you reach them? Try this:
Example:
MatchCollection matchs = Regex.Matches(input, #"\((\d,\d)\)");
foreach (Match m in matchs)
{
rtb1.Text += "\n\n" + m.Captures[0].Value;
}
Try looking at this pattern:
(\((?:\d,\d)\))+
+ allows that the group is repeating and can occur one or more time.
You need to use lookarounds.
string input = #"(1,2)(3,4)";
foreach (Match match in Regex.Matches(input, #"(?<=\().*?(?=\))"))
Console.WriteLine(match.Value);
If your string may have other content then digits in brackets, and you need only those with digits inside, you can use more specific regex as follows.
string input = #"(1,2)(3,4)";
foreach (Match match in Regex.Matches(input, #"(?<=\()\d,\d(?=\))"))
Console.WriteLine(match.Value);

Categories