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;
Related
This question already has an answer here:
Simple and tested online regex containing regex delimiters does not work in C# code
(1 answer)
Closed 3 years ago.
I'm a RegEx novice, so I'm hoping someone out there can give me a hint.
I want to find a straightforward way (using RegEx?) to extract a list/array of values that match a pattern from a string.
If source string is "Hello #bob and #mark and #dave", I want to retrieve a list containing "#bob", "#mark" and "#dave" or, even better, "bob", "mark" and "dave" (without the # symbol).
So far, I have something like this (in C#):
string note = "Hello, #bob and #mark and #dave";
var r = new Regex(#"/(#)\w+/g");
var listOfFound = r.Match(note);
I'm hoping listOfFound will be an array or a List containing the three values.
I could do this with some clever string parsing, but it seems like this should be a piece of cake for RegEx, if I could only come up with the right pattern.
Thanks for any help!
Regexes in C# don't need delimiters and options must be supplied as the second argument to the constructor, but are not required in this case as you can get all your matches using Regex.Matches. Note that by using a lookbehind for the # ((?<=#)) we can avoid having the # in the match:
string note = "Hello, #bob and #mark and #dave";
Regex r = new Regex(#"(?<=#)\w+");
foreach (Match match in r.Matches(note))
Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index);
Output:
Found 'bob' at position 8
Found 'mark' at position 17
Found 'dave' at position 27
To get all the values into a list/array you could use something like:
string note = "Hello, #bob and #mark and #dave";
Regex r = new Regex(#"(?<=#)\w+");
// list of matches
List<String> Matches = new List<String>();
foreach (Match match in r.Matches(note))
Matches.Add(match.Value);
// array of matches
String[] listOfFound = Matches.ToArray();
You could do it without Regex, for example:
var listOfFound = note.Split().Where(word => word.StartsWith("#"));
Replace
var listOfFound = r.Match(note);
by
var listOfFound = r.Matches(note);
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)
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.
This question already has answers here:
Regular Expression Groups in C#
(5 answers)
Closed 6 years ago.
New to using C# Regex, I am trying to capture two comma separated integers from a string into two variables.
Example: 13,567
I tried variations on
Regex regex = new Regex(#"(\d+),(\d+)");
var matches = regex.Matches("12,345");
foreach (var itemMatch in matches)
Debug.Print(itemMatch.Value);
This just captures 1 variable, which is the entire string. I did workaround this by changing the capture pattern to "(\d+)", but that then ignores the middle comma entirely and I would get a match if there were any text between the integers.
How do I get it to extract both integers and ensure it also sees a comma between.
Can do this with String.Split
Why not just use a split and parse?
var results = "123,456".Split(',').Select(int.Parse).ToArray();
var left = results[0];
var right = results[1];
Alternatively, you can use a loop and use int.TryParse to handle failures but for what you're looking for this should cover it
If you're really committed to a Regex
You can do this with a Regex too, just need to use groups of the match
Regex r = new Regex(#"(\d+)\,(\d+)", RegexOptions.Compiled);
var r1 = r.Match("123,456");
//first is total match
Console.WriteLine(r1.Groups[0].Value);
//Then first and second groups
var left = int.Parse(r1.Groups[1].Value);
var right = int.Parse(r1.Groups[2].Value);
Console.WriteLine("Left "+ left);
Console.WriteLine("Right "+right);
Made a dotnetfiddle you can test the solution in as well
With Regex, you can use this:
Regex regex = new Regex(#"\d+(?=,)|(?<=,)\d+");
var matches = regex.Matches("12,345");
foreach (Match itemMatch in matches)
Console.WriteLine(itemMatch.Value);
prints:
12
345
Actually this is doing a look-ahead and look-behind a , :
\d+(?=,) <---- // Match numbers followed by a ,
| <---- // OR
(?<=,)\d+ <---- // Match numbers preceeded by a ,
This question already has answers here:
My regex is matching too much. How do I make it stop? [duplicate]
(5 answers)
Closed 6 years ago.
I couldn't seem to find a match for this question so my apologies in advance if it's a duplicate.
Given the template: <<FirstName>> << FirstName >>
I want to replace both strings between the '<<>>''s using a single regex that should match both.
The following code doesn't seem to work the way I'm expecting:
[Test]
public void ShouldReplaceMultiple()
{
var pattern = "<<.*FirstName.*>>";
var template = "<<FirstName>> <<FirstName>>";
var replaceWith = "FOO";
var regex = new Regex(pattern);
Assert.AreEqual("FOO FOO", regex.Replace(template, replaceWith));
}
The output of the test is as follows:
Expected string length 7 but was 3. Strings differ at index 3.
Expected: "FOO FOO"
But was: "FOO"
--------------^
I don't understand why both strings won't be replaced?
Make it non-greedy using .*?
var pattern = "<<.*?FirstName.*?>>";
var template = "<<FirstName>> <<FirstName>>";
var replaceWith = "FOO";
var regex = new Regex(pattern);
Console.WriteLine(regex.Replace(template, replaceWith));
Ideone Demo
If you want to deal only with spaces in between the <<>>, then this will suffice
<<\s*?FirstName\s*?>>
string pattern = #"<<(?<=<<)\s*FirstName\s*(?=>>)>>";
var template = "<<FirstName>> <<FirstName>>";
var replaceWith = "FOO";
var regex = new Regex(pattern);
Assert.AreEqual("FOO FOO", regex.Replace(template, replaceWith));