C# Regex is matching too much - c#

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

Related

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 match between two strings that might contain another string

I'm doing a regex that is trying to match the following string:
.\SQL2012
From the two strings (they are contained within another larger string but that is irrelevant in this case):
/SERVER "\".\SQL2012\""
/SERVER .\SQL2012
So the "\" before and the \"" after the match may both be omitted in some cases. The regex I've come up with (from a previous question here on StackOverflow) is the following:
(?<=\/SERVER\s*(?:[""\\""]+)?)\w+(?=(?:[\\""""]+|$)| )
Which works fine if I'm trying to match TEST_SERVER instead of .\SQL2012 (because \w does not match special characters). Is there a way to match anything until \"" or a whitespace occurs?
I'm doing this in C#, here's my code:
string input = "/SERVER \"\\\".\\SQL2012\\\"\"";
string pattern = #"(?<=\/SERVER\s*(?:[""\\""]+)?)\w+(?=(?:[\\""""]+|$)| )";
Regex regEx = new Regex(pattern);
MatchCollection matches = regEx.Matches(input);
foreach (Match match in matches)
{
Console.WriteLine(match.ToString());
}
Console.ReadKey();
Add a word boundary \b just before to the lookahead,
string input = "/SERVER .\\SQL2012";
Regex rgx = new Regex(#"(?<=\/SERVER\s+""\\"").*?\b(?=\\""""|$| )|(?<=\/SERVER\s+).*?\b(?= |$)");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[0].Value);
Console.WriteLine(input);
IDEONE

MatchCollection and Regex Matches weird behaviour

When I try to use a Regex to split a string the MatchCollection returned by .Matches only contain the string it self and not the group.
So here is my regex : string pattern = #"^(\w[.])\s*(\w+)$";
and a sample string : W.Test
I expect the MatchCollection to have 2 elements W. and Test but it looks like it doesnt work.
You need to return the matched context from your capturing groups. The Groups property gets the captured groups within the regular expression.
string pattern = #"^(\w[.])\s*(\w+)$";
string input = "W.Test";
Match match = Regex.Match(input, pattern);
if (match.Success) {
Console.WriteLine(match.Groups[1].Value); //=> 'W.'
Console.WriteLine(match.Groups[2].Value); //=> 'Test'
}
Try this
Match match = Regex.Match(input, #" ^(?<firstGroup>\w[.])\s*(?<SecondGroup>\w+)$", RegexOptions.IgnoreCase);
var firstGroup = match.Groups["firstGroup"].Value

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