Regex - replacing chars in C# string in specific cases - c#

I want to replace all brackets to another in my input string only when between them there aren't digits. I wrote this working sample of code:
string pattern = #"(\{[^0-9]*?\})";
MatchCollection matches = Regex.Matches(inputString, pattern);
if(matches != null)
{
foreach (var match in matches)
{
string outdateMatch = match.ToString();
string updateMatch = outdateMatch.Replace('{', '[').Replace('}', ']');
inputString = inputString.Replace(outdateMatch, updateMatch);
}
}
So for:
string inputString = "{0}/{something}/{1}/{other}/something"
The result will be:
inputString = "{0}/[something]/{1}/[other]/something"
Is there possibility to do this in one line using Regex.Replace() method?

You may use
var output = Regex.Replace(input, #"\{([^0-9{}]*)}", "[$1]");
See the regex demo.
Details
\{ - a { char
([^0-9{}]*) - Capturing group 1: 0 or more chars other than digits, { and }
} - a } char.
The replacement is [$1], the contents of Group 1 enclosed with square brackets.

Regex.Replace(input, #"\{0}/\{(.+)\}/\{1\}/\{(.+)}/(.+)", "{0}/[$1]/{1}/[$2]/$3")

Could you do this?
Regex.Replace(inputString, #"\{([^0-9]*)\}", "[$1]");
That is, capture the "number"-part, then just return the string with the braces replaced.
Not sure if this is exactly what you are after, but it seems to fit the question :)

Related

Regex for this formula

I'm struggling with making a regex for this type of formula: LU1O/00054362/8. I'd like to receive only the first part - LU1O every time. It's always letter, letter, number, letter. Please help me with suggestion.
try this:
string input = #"LU1O/00054362/8";
var regex = "^[A-Z]{2}[0-9][A-Z]$";
var match = Regex.Match(input.Substring(0,4), regex, RegexOptions.IgnoreCase);
if (match.Success)
{
//matched
}
or
string input2 = #"LU1O/00054362/8";
var regex2= "^[A-Z]{2}[0-9][A-Z]";
var match2 = Regex2.Match(input2, regex2, RegexOptions.IgnoreCase);
if (match2.Success)
{
//matched
}
If '/' is always a delimiter you could string.split('/') and access the first element from the resulting array.

Regex - Removing specific characters before the final occurance of #

So, I'm trying to remove certain characters [.&#] before the final occurance of an #, but after that final #, those characters should be allowed.
This is what I have so far.
string pattern = #"\.|\&|\#(?![^#]+$)|[^a-zA-Z#]";
string input = "username#middle&something.else#company.com";
// input, pattern, replacement
string result = Regex.Replace(input, pattern, string.Empty);
Console.WriteLine(result);
Output: usernamemiddlesomethingelse#companycom
This currently removes all occurances of the specified characters, apart from the final #. I'm not sure how to get this to work, help please?
You may use
[.&#]+(?=.*#)
Or, equivalent [.&#]+(?![^#]*$). See the regex demo.
Details
[.&#]+ - 1 or more ., & or # chars
(?=.*#) - followed with any 0+ chars (other than LF) as many as possible and then a #.
See the C# demo:
string pattern = #"[.&#]+(?=.*#)";
string input = "username#middle&something.else#company.com";
string result = Regex.Replace(input, pattern, string.Empty);
Console.WriteLine(result);
// => usernamemiddlesomethingelse#company.com
Just a simple solution (and alternative to complex regex) using Substring and LastIndexOf:
string pattern = #"[.#&]";
string input = "username#middle&something.else#company.com";
string inputBeforeLastAt = input.Substring(0, input.LastIndexOf('#'));
// input, pattern, replacement
string result = Regex.Replace(inputBeforeLastAt, pattern, string.Empty) + input.Substring(input.LastIndexOf('#'));
Console.WriteLine(result);
Try it with this fiddle.

Problems with regex in c# only returning a single match

I'm building a regex and I'm missing something as it's not working properly.
my regex logic is trying to look for anything that has #anychars# and return the number of matches on the sentence and not a single match.
Here are a few examples
1- #_Title_# and #_Content_# should return two matches: #_Title_# and #_Content_#.
2- Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_# should return 3 matches: #_TemplateName_# #_Full_Product_Name_# and #_Short_Description_#
and so on. Here is what my regex looks like: ^(.*#_.*_#.*)+$
any thoughts on what I'm doing wrong?
Something as simple as:
#.*?#
Or:
#_.*?_#
If you are trying to match the underscores too (it wasn't clear in the original version of the question). Or:
#_(.*?)_#
Which makes it easier to extract the token between your #_ and _# delimiters as a group.
Should work. The *? is key. It's non-greedy. Otherwise you match everything between the first and last #
So for example:
var str = "Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_#";
var r = new Regex("#_(.*?)_#");
foreach (Match m in r.Matches(str))
{
Console.WriteLine(m.Value + "\t" + m.Groups[1].Value);
}
Outputs:
#_TemplateName_#     TemplateName
#_Full_Product_Name_#    Full_Product_Name
#_Short_Description_#    Short_Description
Try this :
string[] inputs = {
"#Title# and #Content#",
"Product #TemplateName# #_Full_Product_Name_# more text. text text #_Short_Description_#"
};
string pattern = "(?'string'#[^#]+#)";
foreach (string input in inputs)
{
MatchCollection matches = Regex.Matches(input, pattern);
Console.WriteLine(string.Join(",",matches.Cast<Match>().Select(x => x.Groups["string"].Value).ToArray()));
}
Console.ReadLine();
You regular expression is not correct. In addition, you want to loop through match if you want all matching.
static void Main(string[] args)
{
string input = "Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_#",
pattern = "#_[a-zA-Z_]*_#";
Match match = Regex.Match(input, pattern);
while (match.Success)
{
Console.WriteLine(match.Value);
match = match.NextMatch();
}
Console.ReadLine();
}
Result
Don't use anchors and change your regex to:
(#[^#]+#)
In regex the [^#] expression means any character BUT #
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = #"(#[^#]+#)";
Regex rgx = new Regex(pattern);
string sentence = "#blah blah# asdfasdfaf #somethingelse#";
foreach (Match match in rgx.Matches(sentence))
Console.WriteLine("Found '{0}' at position {1}",
match.Value, match.Index);
}
}

How to search characters between #, but do not use # in combination &#60 in C#

I need help with this Regex.
I have string:
text1#text2&#60&#61#text3#56&*()_!
I have to get: text1, text2&#60&#61, text3, 56&*()_!
How to search characters between #, but do not use # in combination &#60 and &#61 (pattern: &#\d+)
The regular expression will be used in C#.
Now I use this pattern .*?(?=#)|.*?$
Just split the string according to # which was preceded by a number.
string value = "text1#text2&#60&#61#text3#56&*()_!";
string[] lines = Regex.Split(value, #"(?<=\d)#");
foreach (string line in lines) {
Console.WriteLine(line);
}
IDEONE
Thank a lot for your answer, but I found the best way
string value = "text1#text2&#60&#61#text3#56&*()_!";
string splitPattern = #"(?<!&)#|#(?!\d+)";
List<string> values = Regex.Split(value, splitPattern).Where(s => s != String.Empty);

how to remove special char from the string and make new string?

I have a string 4(4X),4(4N),3(3X) from this string I want to make string 4,4,3. If I am getting the string 4(4N),3(3A),2(2X) then I want to make my string 4,3,2.
Please someone tell me how can I solve my problem.
This Linq query selects substring from each part of input string, starting from beginning till first open brace:
string input = "4(4N),3(3A),2(2X)";
string result = String.Join(",", input.Split(',')
.Select(s => s.Substring(0, s.IndexOf('('))));
// 4,3,2
This may help:
string inputString = "4(4X),4(4N),3(3X)";
string[] temp = inputString.Split(',');
List<string> result = new List<string>();
foreach (string item in temp)
{
result.Add(item.Split('(')[0]);
}
var whatYouNeed = string.Join(",", result);
You can use regular expressions
String input = #"4(4X),4(4N),3(3X)";
String pattern = #"(\d)\(\1.\)";
// ( ) - first group.
// \d - one number
// \( and \) - braces.
// \1 - means the repeat of first group.
String result = Regex.Replace(input, pattern, "$1");
// $1 means, that founded patterns will be replcaed by first group
//result = 4,4,3

Categories