Regex.Matches doesn't find match [duplicate] - c#

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)

Related

C# - Can you do an array of Regex search patterns? [duplicate]

This question already has answers here:
Declare a List and populate with values using one code statement [closed]
(5 answers)
Closed 3 years ago.
I'm a network engineer working with multiple version of Cisco's IOS and need to use multiple regular expression patterns. Is there a way to build an array of regex patterns?
I've used regex patterns in various other programs, but when I started building this I have 3 pattern formats to search for so far and will be adding more as I go through our network, no doubt.
I've tried the usual:
Regex someVariable[] = new Regex();
This is currently what I have and would like to clean this up into an array for future loop searches through the patterns or so I can just call them individually as needed someVariable[0], etc.
Regex intRegex = new Regex(#"((?<!\S)[A-Za-z]{2}\d{1,5}\S+\s+)|(\s[A-Za-z]{7,15}\d{1,5}\S+\s+)", RegexOptions.Compiled);
Regex psRegex = new Regex(#", id\s+\d{10},", RegexOptions.Compiled);
Regex cidRegex = new Regex(#"\d{3}-\d{3}-\d{4}", RegexOptions.Compiled);
Regex vcidRegex = new Regex(#"vcid\s\d{10},", RegexOptions.Compiled);
I'm not sure what my options are with c# as I've never walked down this path with c# before and in the past have only ever used 1 or maybe 2 Regex search patterns in an entire program before.
Try this
Regex[] regexCollection = new Regex[4];
Regex intRegex = new Regex(#"((?<!\S)[A-Za-z]{2}\d{1,5}\S+\s+)|(\s[A-Za-z]{7,15}\d{1,5}\S+\s+)", RegexOptions.Compiled);
Regex psRegex = new Regex(#", id\s+\d{10},", RegexOptions.Compiled);
Regex cidRegex = new Regex(#"\d{3}-\d{3}-\d{4}", RegexOptions.Compiled);
Regex vcidRegex = new Regex(#"vcid\s\d{10},", RegexOptions.Compiled);
regexCollection[0] = intRegex;
regexCollection[1] = psRegex;
regexCollection[2] = intRegex;
regexCollection[3] = vcidRegex;

RegEx in C# Replace Method [duplicate]

This question already has answers here:
C#: How to Delete the matching substring between 2 strings?
(6 answers)
Closed 4 years ago.
I am trying to write the RegEx for replacing "name" part in below string.
\profile\name\details
Where name: -Can have special characters
-No spaces
Let's say I want to replace "name" in above path with ABCD, the result would be
\profile\ABCD\details
What would be the RegEx to be used in Replace for this?
I have tried [a-zA-Z0-9##$%&*+\-_(),+':;?.,!\[\]\s\\/]+$ but it's not working.
As your dynamic part is surrounded by two static part you can use them to find it.
\\profile\\(.*)\\details
Now if you want to replace only the middle part you can either use LookAround.
string pattern = #"(?<=\\profile\\).*(?=\\details)";
string substitution = #"titi";
string input = #"\profile\name\details
\profile\name\details
";
RegexOptions options = RegexOptions.Multiline;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
Or use the replacement patterns $GroupIndex
string pattern = #"(\\profile\\)(.*)(\\details)";
string substitution = #"$1Replacement$3";
string input = #"\profile\name\details
\profile\name\details
";
RegexOptions options = RegexOptions.Multiline;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
For readable nammed group substitution is a possibility.

Replace text place holders with Regular Expression [duplicate]

This question already has answers here:
Extract string between braces using RegEx, ie {{content}}
(3 answers)
Closed 6 years ago.
I have a text template that has text variables wrapped with {{ and }}.
I need a regular expression to gives me all the matches that "Include {{ and }}".
For example if I have {{FirstName}} in my text I want to get {{FirstName}} back as a match to be able to replace it with the actual variable.
I already found a regular expression that probably gives me what is INSIDE { and } but I don't know how can I modify it to return what I want.
/\{([^)]+)\}/
This pattern should do the trick:
string str = "{{FirstName}} {{LastName}}";
Regex rgx = new Regex("{{.*?}}");
foreach (var match in rgx.Matches(str))
{
// {{FirstName}}
// {{LastName}}
}
Maybe:
alert(/^\{{2}[\w|\s]+\}{2}$/.test('{{FirstName}}'))
^: In the beginning.
$: In the end.
\{{2}: Character { 2 times.
[\w|\s]+: Alphabet characters or whitespace 1 or more times.
\}{2}: Character } 2 times.
UPDATE:
alert(/(^\{{2})?[\w|\s]+(\}{2})?$/.test('FirstName'))

Escaping characters in RegEx pattern string [duplicate]

This question already has answers here:
Escape Special Character in Regex
(3 answers)
Closed 7 years ago.
I'm trying to extract MTQ0ODQ3NjcyNDoxNDQ4NDc2NzI0OjE6LTM4OTc1OTc2MjM4MDc1OTM2NjY6MTQ0ODQ3NjAwMzowOjA6NTQw from the string below.
I am having issues with the \\ (backslash) characters. How do I escape these in C#. Is there any documentation that shows characters that need escaping in regex patterns, and how to escape them?
first_cursor\\":\\"MTQ0ODQ3NjcyNDoxNDQ4NDc2NzI0OjE6LTM4OTc1OTc2MjM4MDc1OTM2NjY6MTQ0ODQ3NjAwMzowOjA6NTQw\\"
I've tried the following to no avail. I tried to avoid having to escape the backslashes altogether:
MatchCollection matches = Regex.Matches(content, "first_cursor*.quot;([-0-9A-Za-z]+)");
Any help would be much appreciated.
In C# each backslash in a string can be written as \\\\.
You can use the following:
MatchCollection matches = Regex.Matches(content, "first_cursor\\\\{2}":\\\\{2}&quot([-0-9A-Za-z]+)");
I prefer to use verbatim string literals when writing RegEx strings in C#:
string pattern = #"first_cursor\\\\":\\\\"([-0-9A-Za-z]+)\\\\"";
This prevents you from having to escape the slashes twice; once for C# and again for the RegEx engine.
As an aside, this syntax is also useful when storing paths in strings:
string logFile = #"C:\Temp\mylog.txt";
And even supports multi-line for SQL commands and such:
string query = #"
SELECT *
FROM tblStudents
WHERE FirstName = 'Bobby'
AND LastName = 'Tables'
";
You can use lookahead to elimate some of the contenders:
var example = #"first_cursor\\":\\"MTQ0ODQ3NjcyNDoxNDQ4NDc2NzI0OjE6LTM4OTc1OTc2MjM4MDc1OTM2NjY6MTQ0ODQ3NjAwMzowOjA6NTQw\\"";
var regex = new Regex("(?<!&[-0-9A-Za-z]*)(?<!_[-0-9A-Za-z]*)[-0-9A-Za-z]+");
var matches = regex.Matches(example);
foreach(var match in matches)
{
if (match.ToString() != "first")
{
Console.WriteLine(match);
}
}
This would give you two matches. One for first and one for the string you are looking for. Then you can iterate over the matches and see if it's not "first" then it should be what you are looking for.

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