Regex to parse string input - c#

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);

Related

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);
}

Match with blank and without blank

I want or get the name of mp3
I'm currently using this code
string str = "onClick=\"playVideo('upload/honour-3.mp3',this)\"/> onClick=\"playVideo('upload/honor is my honor .mp3',this)\"/> onClick=\"playVideo('upload/honour-6.mp3',this)\"/> ";
string Pattern = #"playVideo\(\'upload\/(?<mp3>\S*).mp3\'\,this\)";
if (Regex.IsMatch(str, Pattern))
{
MatchCollection Matches = Regex.Matches(str, Pattern);
foreach (Match match in Matches)
{
string fn = match.Groups["mp3"].Value;
Debug.Log(match.Groups["mp3"].Value);
}
}
But \ S * matches only like
honour-3
honour-6
i can't get "honor is my honor "
i try the"\S*\s*",but it not work
I have a lot of how many blank string uncertain
How do I use Regex to get mp3's name?
If you dont have to match "playVideo" and "upload", Your regex is unnecessarily complicated. This one produces the expected results:
#"[\w\s-]+\.mp3"
Results:
"honour-3.mp3",
"honor is my honor .mp3",
"honour-6.mp3"
If you don't want .mp3 at the end of the matches, you can change the regex to #"([\w\s-]+)\.mp3" and select the second group (the first one is the whole match).
Regex.Matches(str, #"([\w\s-]+)\.mp3").Cast<Match>().Select(m => m.Groups[1].Value).ToArray();
Results:
"honour-3",
"honor is my honor ",
"honour-6"

How do I extract a string of text that lies between *>...* using .NET C# regex or anything else?

I have a string like this.
*>-0.0532*>-0.0534*>-0.0534*>-0.0532*>-0.0534*>-0.0534*>-0.0532*>-0.0532*>-0.0534*>-0.0534*>-0.0534*>-0.0532*>-0.0534*
I wanna extract between *> and * characters.
I tried this pattern which is wrong here below:
string pattern = "\\*\\>..\\*";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(seriGelen);
if (matches.Count > 0)
{
foreach (Match match in matches)
MessageBox.Show("{0}", match.Value);
}
You can use simple regex:
(?<=\*>).*?(?=\*)
Sample code:
string text = "*>-0.0532*>-0.0534*>-0.0534*>-0.0532*>-0.0534*>-0.0534*>-0.0532*>-0.0532*>-0.0534*>-0.0534*>-0.0534*>-0.0532*>-0.0534*";
string[] values = Regex.Matches(text, #"(?<=\*>).*?(?=\*)")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
Looks like there are can be very different values (UPD: there was an integer positive value). So, let me to not check numbers format. Also I will consider that *> and >, and also * are just different variants of delimiters.
I'd like to suggest the following solution.
(?<=[>\*])([^>\*]+?)(?=[>\*]+)
(http://regex101.com/r/mM7nK1)
Not sure it is ideal. Will only works if your input starts and ends with delimiters, but will allow to you to use matches instead groups, as your code does.
========
But you know, why wouldn't you use String.Split function?
var toprint = seriGelen.Split(new [] {'>', '*'}, StringSplitOptions.RemoveEmptyEntries);
Is there an error at the beginning of the string? Missing an asterisk after first number? >-0.0532>-0.0534*>
If not try this.
>([-+]?[0-9]*\.?[0-9]+)\*
C# Code
string strRegex = #">([-+]?[0-9]*\.?[0-9]+)\*";
Regex myRegex = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
string strTargetString = #">-0.0532>-0.0534*>-0.0534*>-0.0532*>-0.0534*>-0.0534*>-0.0532*>-0.0532*>-0.0534*>-0.0534*>-0.0534*>-0.0532*>-0.0534*";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}

Find each RegEx match in string

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());
}

Categories