Change in string some part, but without one part - where are numbers - c#

For example I have such string:
ex250-r-ninja-08-10r_
how could I change it to such string?
ex250 r ninja 08-10r_
as you can see I change all - to space, but didn't change it where I have XX-XX part... how could I do such string replacement in c# ? (also string could be different length)
I do so for -
string correctString = errString.Replace("-", " ");
but how to left - where number pattern XX-XX ?

You can use regular expressions to only perform substitutions in certain cases. In this case, you want to perform a substitution if either side of the dash is a non-digit. That's not quite as simple as it might be, but you can use:
string ReplaceSomeHyphens(string input)
{
string result = Regex.Replace(input, #"(\D)-", "${1} ");
result = Regex.Replace(result, #"-(\D)", " ${1}");
return result;
}
It's possible that there's a more cunning way to do this in a single regular expression, but I suspect that it would be more complicated too :)

A very uncool approach using a StringBuilder. It'll replace all - with space if the two characters before and the two characters behind are not digits.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < text.Length; i++)
{
bool replace = false;
char c = text[i];
if (c == '-')
{
if (i < 2 || i >= text.Length - 2) replace = true;
else
{
bool leftDigit = text.Substring(i - 2, 2).All(Char.IsDigit);
bool rightDigit = text.Substring(i + 1, 2).All(Char.IsDigit);
replace = !leftDigit || !rightDigit;
}
}
if (replace)
sb.Append(' ');
else
sb.Append(c);
}

Since you say you won't have hyphens at the start of your string then you need to capture every occurrence of - that is preceded by a group of characters which contains at least one letter and zero or many numbers. To achieve this, use positive lookbehind in your regex.
string strRegex = #"(?<=[a-z]+[0-9]*)-";
Regex myRegex = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline);
string strTargetString = #"ex250-r-ninja-08-10r_";
string strReplace = #" ";
return myRegex.Replace(strTargetString, strReplace);
Here are the results:

Related

Replace only 'n' occurences of a substring in a string in C#

I have a input string like -
abbdabab
How to replace only the 2nd, 3rd and subsequent occurances of the substring "ab" with any random string like "x" keeping the original string intact. Example in this case -
1st Output - xbdabab 2nd Output - abbdxab 3rd Output - abbdabx and so on...
I have tried using Regex like -
int occCount = Regex.Matches("abbdabab", "ab").Count;
if (occCount > 1)
{
for (int i = 1; i <= occCount; i++)
{
Regex regReplace = new Regex("ab");
string modifiedValue = regReplace.Replace("abbdabab", "x", i);
//decodedMessages.Add(modifiedValue);
}
}
Here I am able to get the 1st output when the counter i value is 1 but not able to get the subsequent results. Is there any overloaded Replace method which could achieve this ? Or Can anyone help me in pointing where I might have gone wrong?
You can try IndexOf instead of regular expressions:
string source = "abbdabab";
string toFind = "ab";
string toSet = "X";
for (int index = source.IndexOf(toFind);
index >= 0;
index = source.IndexOf(toFind, index + 1)) {
string result = source.Substring(0, index) +
toSet +
source.Substring(index + toFind.Length);
Console.WriteLine(result);
}
Outcome:
Xbdabab
abbdXab
abbdabX
You can use a StringBuilder:
string s = "abbdabab";
var matches = Regex.Matches(s, "ab");
StringBuilder sb = new StringBuilder(s);
var m = matches[0]; // 0 for first output, 1 for second output, and so on
sb.Remove(m.Index, m.Length);
sb.Insert(m.Index, "x");
var result = sb.ToString();
Console.WriteLine(result);
You may use a dynamically built regex to be used with regex.Replace directly:
var s = "abbdabab";
var idx = 1; // First = 1, Second = 2
var search = "ab";
var repl = "x";
var pat = new Regex($#"(?s)((?:{search}.*?){{{idx-1}}}.*?){search}"); // ((?:ab.*?){0}.*?)ab
Console.WriteLine(pat.Replace(s, $"${{1}}{repl}", 1));
See the C# demo
The pattern will look like ((?:ab.*?){0}.*?)ab and will match
(?s) - RegexOptions.Singleline to make . also match newlines
((?:ab.*?){0}.*?) - Group 1 (later, this value will be put back into the result with ${1} backreference)
(?:ab.*?){0} - 0 occurrences of ab followed with any 0+ chars as few as possible
.*? - any 0+ chars as few as possible
ab - the search string/pattern.
The last argument to pat.Replace is 1, so that only the first occurrence could be replaced.
If search is a literal text, you need to use var search = Regex.Escape("a+b");.
If the repl can have $, add repl = repl.Replace("$", "$$");.

Replace Only Multiples Of three in c#

How can I replace only multiples of 3 in C#? Say for example I had the string "000100000", and I wanted "000" to be replaced with "+" but only every group of three characters. Additional condition: the groups should be changed starting from the end:, e.g. for "000100000" it should output "+100+".
You can just use a regular expression for this.
(0{3}(?!0+))
This uses a negative lookahead to make sure there aren't any other zeros after a group of three 0s - in other words, for a sequence of an arbitrary number of 0s, it'll only match the last 3.
You can modify this if you want to do something subtly different looking lookaheads and lookbehinds.
I suggest using regular expressions, e.g.:
string source = "000100000";
// "+100+"
string result = Regex.Replace(
source,
"0{3,}",
match => new string('0', match.Length % 3) + new string('+', match.Length / 3));
Tests:
001 -> 001
0001 -> +1
000100 -> +100
0001000 -> +1+
00010000 -> +10+
000100000 -> +100+
0001000000 -> +1++
You can do this with Substring:
string strReplace = "000100000";
//Store your string on StringBuilder to edit the string
StringBuilder sb = new StringBuilder();
sb.Append("+");
sb.Append(strReplace.Substring(0, 3)); //Use substring, 0 is the start of index and 3 is the length as your requirement
sb.Append("+");
sb.Append(strReplace.Substring(3, 3));
sb.Append("+");
sb.Append(strReplace.Substring(6, 3));
sb.Append("+");
strReplace = sb.ToString(); //Finally replace your string instance with your result
Or by for loop but this time instead of using substring, we use Char array to get every char in your string:
string strReplace = "000100000";
char[] chReplace = strReplace.ToCharArray();
StringBuilder sb = new StringBuilder();
for (int x = 0; x <= 8; x++)
{
if (x == 0 || x == 3 || x == 6 || x == 9)
{
sb.Append("+");
sb.Append(chReplace[x]);
}
else
{
sb.Append(chReplace[x]);
}
}
sb.Append("+");
strReplace = sb.ToString();
Okay, a bunch of these answers are addressing detecting groups of 3 '0's. Here's an answer that deals with groups of 3 anythings (reading the string in groups of three characters):
string GroupsOfThree(string str)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i + 2 < str.Length; i += 3)
{
string sub = str.Substring(i, 3);
if (sub.All(c => c == sub[0]))
sb.Append("+");
else
sb.Append(sub);
}
return sb.ToString();
}
You can use a replace regular expression.
"[0]{3}|[1]{3}"
The above Regular Expression can be use like below in C#:
string k = "000100000";
Regex pattern = new Regex("[0]{3}|[1]{3}");
pattern.Replace(k, "+");
reversing the string before you replace and after solves your problem.
something like:
string ReplaceThreeZeros(string text)
{
var reversed = new string(text.Reverse().ToArray());
var replaced = reversed.Replace("000","+");
return new string(replaced.Reverse().ToArray());
}

Regular expression help - ignoring parenthesis, ands, ors and whitespace again

Consider the following english phrase
FRIEND AND COLLEAGUE AND (FRIEND OR COLLEAGUE AND (COLLEAGUE AND FRIEND AND FRIEND))
I want to be able to programmatically change arbitrary phrases, such as above, to something like:
SELECT * FROM RelationTable R1 JOIN RelationTable R2 ON R2.RelationName etc etc WHERE
R2.RelationName = FRIEND AND R2.RelationName = Colleague AND (R3.RelationName = FRIENd,
etc. etc.
My question is. How do I take the initial string, strip it of the following words and symbols : AND, OR, (, ),
Then change each word, and create a new string.
I can do most of it, but my main problem is that if I do a string.split and only get the words I care for, I can't really replace them in the original string because I lack their original index. Let me explain in a smaller example:
string input = "A AND (B AND C)"
Split the string for space, parenthesies, etc, gives: A,B,C
input.Replace("A", "MyRandomPhrase")
But there is an A in AND.
So I moved into trying to create a regular expression that matches exact words, post split, and replaces. It started to look like this:
"(\(|\s|\))*" + itemOfInterest + "(\(|\s|\))+"
Am I on the right track or am I overcomplicating things..Thanks !
You can try using Regex.Replace, with \b word boundary regex
string input = "A AND B AND (A OR B AND (B AND A AND A))";
string pattern = "\\bA\\b";
string replacement = "MyRandomPhrase";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
class Program
{
static void Main(string[] args)
{
string text = "A AND (B AND C)";
List<object> result = ParseBlock(text);
Console.ReadLine();
}
private static List<object> ParseBlock(string text)
{
List<object> result = new List<object>();
int bracketsCount = 0;
int lastIndex = 0;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (c == '(')
bracketsCount++;
else if (c == ')')
bracketsCount--;
if (bracketsCount == 0)
if (c == ' ' || i == text.Length - 1)
{
string substring = text.Substring(lastIndex, i + 1 - lastIndex).Trim();
object itm = substring;
if (substring[0] == '(')
itm = ParseBlock(substring.Substring(1, substring.Length - 2));
result.Add(itm);
lastIndex = i;
}
}
return result;
}
}

How to insert spaces between the characters of a string

Is there an easy method to insert spaces between the characters of a string? I'm using the below code which takes a string (for example ( UI$.EmployeeHours * UI.DailySalary ) / ( Month ) ) . As this information is getting from an excel sheet, i need to insert [] for each columnname. The issue occurs if user avoids giving spaces after each paranthesis as well as an operator. AnyOne to help?
text = e.Expression.Split(Splitter);
string expressionString = null;
for (int temp = 0; temp < text.Length; temp++)
{
string str = null;
str = text[temp];
if (str.Length != 1 && str != "")
{
expressionString = expressionString + "[" + text[temp].TrimEnd() + "]";
}
else
expressionString = expressionString + str;
}
User might be inputing something like (UI$.SlNo-UI+UI$.Task)-(UI$.Responsible_Person*UI$.StartDate) while my desired output is ( [UI$.SlNo-UI] + [UI$.Task] ) - ([UI$.Responsible_Person] * [UI$.StartDate] )
Here is a short way to insert spaces after every single character in a string (which I know isn't exactly what you were asking for):
var withSpaces = withoutSpaces.Aggregate(string.Empty, (c, i) => c + i + ' ');
This generates a string the same as the first, except with a space after each character (including the last character).
You can do that with regular expressions:
using System.Text.RegularExpressions;
class Program {
static void Main() {
string expression = "(UI$.SlNo-UI+UI$.Task)-(UI$.Responsible_Person*UI$.StartDate) ";
string replaced = Regex.Replace(expression, #"([\w\$\.]+)", " [ $1 ] ");
}
}
If you are not familiar with regular expressions this might look rather cryptic, but they are a powerful tool, and worth learning. In case, you may check how regular expressions work, and use a tool like Expresso to test your regular expressions.
Hope this helps...
Here is an algorithm that does not use regular expressions.
//Applies dobule spacing between characters
public static string DoubleSpace(string s)
{
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
char[] a = s.ToCharArray();
char[] b = new char[ (a.Length * 2) - 1];
int bIndex = 0;
for(int i = 0; i < a.Length; i++)
{
b[bIndex++] = a[i];
//Insert a white space after the char
if(i < (a.Length - 1))
{
b[bIndex++] = ' ';
}
}
return new string(b);
}
Well, you can do this by using Regular expressions, search for specific paterns and add brackets where needed. You could also simply Replace every Paranthesis with the same Paranthesis but with spaces on each end.
I would also advice you to use StringBuilder aswell instead of appending to an existing string (this creates a new string for each manipulation, StringBuilder has a smaller memory footprint when doing this kind of manipulation)

C# String replacement using Regex

I currently have the code below, to replace a characters in a string but I now need to replace characters within the first X (in this case 3) characters and leave the rest of the string. In my example below I have 51115 but I need to replace any 5 within the first 3 characters and I should end up with 61115.
My current code:
value = 51115;
oldString = 5;
newString = 6;
result = Regex.Replace(value.ToString(), oldString, newString, RegexOptions.IgnoreCase);
result is now 61116. What would you suggest I do to query just the first x characters?
Thanks
Not particularly fancy, but only give regex the data it should be replacing; only send in the range of characters that should potentially be replaced.
result = Regex.Replace(value.ToString().Substring(0, x), oldString, newString, RegexOptions.IgnoreCase);
If you're just replacing a single character only, you could just write the code to do the replacement yourself. It'd be faster than messing with a substring and then a RegEx replace (which is a waste anyway if you're doing a single-char replacement).
StringBuilder sb = new StringBuilder(oldString.Length);
foreach(char c in oldString) {
if(c == replaceFrom) { c = replaceTo; }
sb.Append(c);
}
return sb.ToString();
I think the character-by-character option mentioned here is probably clearer, but if you really want a regex:
string result = "";
int value = 55555;
string oldString = "5";
string newString = "6";
var match = new Regex(#"(\d{1,3})(\d+)?").Match(value.ToString());
if (match.Groups.Count > 1)
result = match.Groups[1].Value.Replace(oldString, newString) + (match.Groups.Count > 2 ? match.Groups[2].Value : "");
I love RegEx, but in this case I would just do a .Replace
string value;
string oldString;
string newString;
value = "51115";
int iLenToLook;
iLenToLook = 3;
oldString = "5";
newString = "6";
string result;
result = value.Length > iLenToLook ? value.Substring(iLenToLook, value.Length - iLenToLook) :"";
result = value.Substring(0, value.Length >= iLenToLook ? iLenToLook : value.Length).Replace(oldString, newString) + result;
EDIT I changed it to get the non-replaced portion first, in case there were replacement strings of differing lengths than the original.
Every time someone in the .NET world has a question about regex, I recommend Expresso (link). It's a great tool for working in the confusing and thorny world of regular expressions.

Categories

Resources