Regex not matching [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Using a regular expression to validate an email address
Email Validation - Regular Expression
I am using following code to validate Email address in C#, but not sure why it fails always:
var regEx = #"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})";
if (Regex.IsMatch(regEx, "abcde#gmail.com", RegexOptions.IgnoreCase))
return true;
else
return false;
Please can someone point out what I am missing here ?

Try this:
[Test]
public void EmailTest()
{
var pattern = #"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
var address = "abcde#gmail.com";
Assert.IsTrue(Regex.IsMatch(address, pattern,RegexOptions.IgnoreCase));
Assert.IsTrue(regex.IsMatch(address));
}
You have the wrong order of string and pattern.
Also check this thread

You've got your IsMatch parameters the wrong way around; the first is the input, the second is the pattern.

Related

Regex.Matches doesn't find match [duplicate]

This question already has answers here:
Why \b does not match word using .net regex
(2 answers)
Closed 3 years ago.
I'm using Visual C# to create a little tool to support some people doing simple text manipulations. The tool has a GUI but uses regex in the code. Most things work already but now I found a problem that I'm not able to solve. I want to find the string MY2020 at the start of a word. Here's my code:
string TestString = "we have the string MY2020 somewhere in the line";
string Pattern = "\bMy2020";
RegexOptions options = RegexOptions.IgnoreCase;
MatchCollection myMatches = Regex.Matches(TestString, Pattern, options);
if (myMatches.Count > 0)
{
I expect MY2020 to be found. So myMatches.Count should be 1, but it's 0.
In parallel I use an online regex tester (https://regex101.com/). This one shows a match.
What am I missing?
You need to escape the "\", I have modified your code as
string TestString = "we have the string MY2020 somewhere in the line";
string Pattern = #"\bMy2020";
RegexOptions options = RegexOptions.IgnoreCase;
MatchCollection myMatches = Regex.Matches(TestString, Pattern, options);
if (myMatches.Count > 0)

Why does Regex.IsMatch return wrong values? [duplicate]

This question already has answers here:
using regex to validate input formatting in C#
(4 answers)
Closed 4 years ago.
With this code, isMatch is false.
var input = "12312345023";
var isMatch = Regex.IsMatch(#"^\d{6,}", input);
And if input = "", isMatch is true. Not sure why it seems to be opposite of what it should be.
If I try the same pattern and input here it works as expected. But when I start a new console app with just that code, isMatch is not correct.
MSDN says:
public static bool IsMatch(
string input,
string pattern
)
Since your parameters are swapped, your pattern is empty. The result will always be true. You need to swap your parameters to get a correct result:
var isMatch = Regex.IsMatch(input, #"^\d{6,}");

C# Regular Expression Capturing Empty String [duplicate]

This question already has answers here:
C# Regex.Split: Removing empty results
(9 answers)
Closed 5 years ago.
I'm trying to create a simple regular expression in C# to split a string into tokens. The problem I'm running into is that the pattern I'm using captures an empty string, which throws off my expected results. What can I do to change my regular expression so it doesn't capture an empty string?
var input = "ID=123&User=JohnDoe";
var pattern = "(?:id=)|(?:&user=)";
var tokens = Regex.Split(input, pattern, RegexOptions.IgnoreCase);
// Expected Results
// tokens[0] == "123"
// tokens[1] == "JohnDoe"
// Actual Results
// tokens[0] == ""
// tokens[1] == "123"
// tokens[2] == "JohnDoe"
While the comments to your OP regarding using a different approach may have merit, they don't address your specific question regarding the RegEx behavior.
I think that the reason though you're getting the regex behavior has to do with an implicit capture group (ed: or it could just be limiting the capture behavior of the first group is sufficient), but I haven't made it to the top level of the RegEx hierarchy of understanding.
Edit:
Working RegEx for the given test case:
(?>id=)|(?:&user=)
If none of this is to your liking, you could always tack a predicate to the tokens list:
tokens.Where(x => !string.IsNullOrWhiteSpace(x))
I don't think you can solve this problem with Regex.Split to be honest. One brute force way to do this is to remove every "":
var input = "ID=123&User=JohnDoe";
var pattern = "(?:id=)|(?:&user=)";
var tokens = Regex.Split(input, pattern, RegexOptions.IgnoreCase).Where(x => x != "");
I think you should use regex that actually captures the tokens in groups.
var input = "ID=123&User=JohnDoe";
var pattern = "id=(.+)&user=(.+)";
var match = Regex.Match(input, pattern, RegexOptions
.IgnoreCase);
match.Groups[1] // 123

Regex only checks first character in string C# [duplicate]

This question already has answers here:
What special characters must be escaped in regular expressions?
(13 answers)
Closed 4 years ago.
Why does the following method only check the first character in the supplied string?
public static bool IsUnicodeSms(string message)
{
var strMap = new Regex(#"^[#£$¥èéùìòÇØøÅå_ÆæßÉ!""#%&'()*+,-./0123456789:;<=>? ¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà^{}\[~]|€]+$");
return !strMap.IsMatch(message);
}
So for example the following string returns false: "abcლ" but "ლabc" returns true.
You have to escape ] with \] and also put the - at the end:
Change this:
var strMap = new Regex(#"^[#£$¥èéùìòÇØøÅå_ÆæßÉ!""#%&'()*+,-./0123456789:;<=>? ¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà^{}\[~]|€]+$");
To this:
var strMap = new Regex(#"^[#£$¥èéùìòÇØøÅå_ÆæßÉ!""#%&'()*+,./0123456789:;<=>? ¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà^{}\[~\]|€-]+$");
Btw, you can improve your regex and use:
var strMap = new Regex(#"^[#£$¥èéùìòÇØøÅå_ÆæßÉ!"#%&'()*+,./\w:;<=>? ¡ÄÖÑܧ¿äöñüà^{}\[~\]|€-]+$");
And not sure if using the ignore case flag might help you to shorten it a little more like this:
var strMap = new Regex(#"(?i)^[#£$¥èéùìòÇøå_Ææß!"#%&'()*+,./\w:;<=>? ¡§¿äöñüà^{}\[~\]|€-]+$");
You copied the code from here.
It's very flawed. It needs more escaping. From Regexp Tutorial - Character Classes or Character Sets:
the only special characters or metacharacters inside a character class are the closing bracket (]), the backslash (\), the caret (^), and the hyphen (-)
So, it needs to be:
new Regex(#"^[#£$¥èéùìòÇØøÅå_ÆæßÉ!""#%&'()*+,\-./0123456789:;<=>? ¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà^{}\[~\]|€]+$");
You can of course improve the regex even further like #Fede demonstrates.

Extract email adresses from text using RegEx c# [duplicate]

This question already has answers here:
How can I validate an email address using a regular expression?
(79 answers)
Closed 8 years ago.
I have code in console app
reg = new Regex(#"/[a-z0-9_\-\+]+#[a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?/i");
string text = "wjeqklejqwek myEmail#hotmail.com a;lekqlwe anothermail#mail.ru";
parseTextByTagName("", text);
MatchCollection coll = reg.Matches(text);
}
when I debug it it shows that the coll is empty could you tell whats problem I am solving it about an hour
try this
string strRegex = #"[A-Za-z0-9_\-\+]+#[A-Za-z0-9\-]+\.([A-Za-z]{2,3})(?:\.[a-z]{2})?";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = #"wjeqklejqwek myEmail#hotmail.com a;lekqlwe anothermail#mail.ru";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}
Your regular expression worked for me if I take out / & /i.
[a-z0-9_\-\+]+#[a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?
alternatively, you can also use this...
/^[\w-\._\+%]+#(?:[\w-]+\.)+[\w]{2,6}$/

Categories