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));
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:
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:
splitting a string based on multiple char delimiters
(7 answers)
Closed 5 years ago.
string test = "Account.Parameters[\"AccountNumber\"].Caption";
string new = test.Trim("[");
I want output "AccoutNumber".
I have tried the below code but not getting the desired result:
string[] test = "Transaction.Parameters[\"ExpOtherX\"].Caption".Split('[');
string newvalue = test[1];
Just use Split with two delimiters:
string[] test = "Transaction.Parameters[\"ExpOtherX\"].Caption".Split('[', ']');
string newvalue = test[1];
You can also use Regex:
string test = "Account.Parameters[\"AccountNumber\"].Caption";
var match = System.Text.RegularExpressions.Regex.Match(test, ".*?\\.Parameters\\[\"(.*?)\"]");
if (match.Success)
{
Console.WriteLine(match.Groups[1].Value);
}
.*? is a non greedy wildcart capture, so it will match your string until it reaches the next part (in our case, it will stop at .Parameters[", match the string, and then at "])
It will match .Parameters["..."]., and extract the "..." part.
you can do a Split to that string...
string test = "Account.Parameters[\"AccountNumber\"].Caption";
string output = test.Split('[', ']')[1];
Console.WriteLine(output);
This question already has answers here:
How to get number from a string
(5 answers)
Closed 7 years ago.
I am quite new to regular expression. My requirement is to extract number from string that includes mix of numbers and characters. I have tried below codes but I can only get the first number from string.
String serialNumber= "000745 TO 000748,00050-00052"
Match match = Regex.Match(serialNumber), #"(\d)+", RegexOptions.IgnoreCase);
if (match.Success)
{
int a = Convert.ToInt32(match); // This part not sure how to do
}
Expected result is:
000745
000748
00050
00052
string strRegex = #"\d+";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = #"000745 TO 000748,00050-00052";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}
You need to loop through your matches to get all the matches.
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}$/