This question already has answers here:
C# string replace does not actually replace the value in the string [duplicate]
(3 answers)
Closed 6 years ago.
I have the following code inside my c# application:-
string[] excludechar = { "|", "\\", "\"", "'", "/", "[", " ]", ":", "<", " >", "+", "=", ",", ";", "?", "*", " #" };
var currentgroupname = curItemSiteName;
for (int i = 0; i < excludechar.Length; i++)
{
if (currentgroupname.Contains(excludechar[i]))
currentgroupname.Replace(excludechar[i], "");
}
site.RootWeb.SiteGroups.Add(currentgroupname)
now in my abive code the currentgroupname variable which i am passing inside the .ADD function will have all the special characters i have replaced inside my for loop. so can anyone adivce if i can modify my code so the .Replace will be actually replacing the original string of the currentgroupname ...
You are not actually assigning the "replaced" string to currentgroupname
string[] excludechar = { "|", "\\", "\"", "'", "/", "[", " ]", ":", "<", " >", "+", "=", ",", ";", "?", "*", " #" };
var currentgroupname = curItemSiteName;
for (int i = 0; i < excludechar.Length; i++)
{
if (currentgroupname.Contains(excludechar[i]))
currentgroupname = currentgroupname.Replace(excludechar[i], "");
}
site.RootWeb.SiteGroups.Add(currentgroupname)
Isn't it easier with some regex?
var input = "<>+--!I/have:many#invalid\\|\\characters";
var result = Regex.Replace(input, #"\W", "");
Console.Write(result); //Ihavemanyinvalidcharacters
Don't forget the using:
using System.Text.RegularExpressions;
Related
I have string:
string mystring = "hello(hi,mo,wo,ka)";
And i need to get all arguments in brackets.
Like:
hi*mo*wo*ka
I tried that:
string res = "";
string mystring = "hello(hi,mo,wo,ka)";
mystring.Replace("hello", "");
string[] tokens = mystring.Split(',');
string[] tokenz = mystring.Split(')');
foreach (string s in tokens)
{
res += "*" + " " + s +" ";
}
foreach (string z in tokenz)
{
res += "*" + " " + z + " ";
}
return res;
But that returns all words before ",".
(I need to return between
"(" and ","
"," and ","
"," and ")"
)
You can try to use \\(([^)]+)\\) regex get the word contain in brackets,then use Replace function to let , to *
string res = "hello(hi,mo,wo,ka)";
var regex = Regex.Match(res, "\\(([^)]+)\\)");
var result = regex.Groups[1].Value.Replace(',','*');
c# online
Result
hi*mo*wo*ka
This way :
Regex rgx = new Regex(#"\((.*)\)");
var result = rgx.Match("hello(hi,mo,wo,ka)");
Split method has an override that lets you define multiple delimiter chars:
string mystring = "hello(hi,mo,wo,ka)";
var tokens = mystring.Replace("hello", "").Split(new[] { "(",",",")" }, StringSplitOptions.RemoveEmptyEntries);
I am trying to process some text with unusual pattern. The text looks like below:
||Names : XYZ DJ Age : 23 Years Location: New York; end;'
2018-03-20 11:59:59.397, mnx=0x0000700, pid=90c9ac, xSG: dlgID:34
AppDlg:774 params: 2018-03-20 11:59:59.397, mnx=0x700000,
pid=090c9ac, lBG: OPCDManager::Response: 0x7f083 2018-03-20
11:59:59.397, mxn=0x000070, pid=f90c9ac, lBG: DlgID:37774 sess:'990'
conID:1 dlClose:false params:
Now, I want to load this data into a text file as below:
XYZ DJ-23 Years-New York,2018-03-20 11:59:59.397, mnx=0x0000700,
pid=90c9ac, xSG: dlgID:34 AppDlg:774 params: XYZ DJ-23 Years-New
York,2018-03-20 11:59:59.397, mnx=0x700000, pid=090c9ac,
lBG: OPCDManager::Response: 0x7f083 XYZ DJ-23 Years-New
York,2018-03-20 11:59:59.397, mxn=0x000070, pid=f90c9ac,
lBG: DlgID:37774 sess:'990' conID:1 dlClose:false params:
I have tried the below code but it does not give me what I want. Instead, it gives me one long text strings instead of several rows:
string linesc = File.ReadAllText(path);
string[] linesx = linesc.Split('|');
foreach (string s in linesx)
{
string new2=s.Replace(Environment.NewLine, " ");
File.AppendAllText(path2 + "myfile.txt", new2 + Environment.NewLine);
}
How can I modify the code so that I get the rows above?
Try the following:
string linesc = File.ReadAllText(path);
string[] linesx = linesc.Split('|');
foreach (string s in linesx)
{
string new2=s.Replace(Environment.NewLine, " ")
.Replace("Names : ", "")
.Replace("Age : ", "")
.Replace("Location : ", "") + "\n";
File.AppendAllText(path2 + "myfile.txt", new2 + Environment.NewLine);
}
I also took care of removing "Name : ", "Age : " and "Location : " from the input.
You can also try this approach:
string text = #"||Names : XYZ DJ
Age : 23 Years
Location: New York; end;'
2018-03-20 11:59:59.397, mnx=0x0000700, pid=90c9ac, xSG: dlgID:34 AppDlg:774 params:
2018-03-20 11:59:59.397, mnx=0x700000, pid=090c9ac, lBG: OPCDManager::Response: 0x7f083
2018-03-20 11:59:59.397, mxn=0x000070, pid=f90c9ac, lBG: DlgID:37774 sess:'990' conID:1 dlClose:false params:";
StringBuilder result = new StringBuilder();
string[] allLines = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
string name = allLines[0].Replace("||Names : ", string.Empty).Trim();
string age = allLines[1].Replace("Age : ", string.Empty).Replace("Years", string.Empty).Trim();
string location = allLines[2].Replace("Location: ", string.Empty).Replace("; end;'", string.Empty).Trim();
for(int i = 3; i < allLines.Length; i++)
{
result.AppendLine($"{name}-{location},{allLines[i].Trim()}");
}
string res = result.ToString();
Console.WriteLine(res);
You have to break this down into several steps:
extract the 'global' information from the first three lines
iterate over the listing lines and concatenate them to the output format
At the moment you are splitting by '|' which results in ["", "", "Names : XYZ ... your whole other text"].
So for example (not tested):
string[] linesc = File.ReadAllText(path).Split(new string[]{Environment.NewLine}, StringSplitOptions.None);
// extract global infos
string[] name = linesc[0].Split(':');
string[] age = linesc[1].Split(':');
string[] location = linesc[2].Split(':');
for (int i=3; i<linesc.Length; i++)
{
// reconcatenate new line
string new2 = name[1] + "-" + age[1] + "-" + location[1] + "," + linesc[i];
File.AppendAllText(path2 + "myfile.txt", new2 + Environment.NewLine);
}
If you also want to get rid of leading/trailing spaces you can use Trim() on each of the string parts.
I'm trying to convert Wordpress sanitize_file_name function from PHP to C# so I can use it to generate unicode slugs for my site's articles on a web app that build myself.
This is my class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
namespace MyProject.Helpers
{
public static class Slug
{
public static string SanitizeFileName(string filename)
{
string[] specialChars = { "?", "[", "]", "/", "\\", "=", "< ", "> ", ":", ";", ",", "'", "\"", "& ", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}" };
filename = MyStrReplace(filename, specialChars, "");
filename = Regex.Replace(filename, #"/[\s-]+/", "-");
filename.TrimEnd('-').TrimStart('-');
filename.TrimEnd('.').TrimStart('.');
filename.TrimEnd('_').TrimStart('_');
return filename;
}
private static string MyStrReplace(string strToCheck, string[] strToReplace, string newValue)
{
foreach (string s in strToReplace)
{
strToCheck = strToCheck.Replace(s, newValue);
}
return strToCheck;
}
// source: http://stackoverflow.com/questions/166855/c-sharp-preg-replace
public static string PregReplace(string input, string[] pattern, string[] replacements)
{
if (replacements.Length != pattern.Length)
throw new ArgumentException("Replacement and Pattern Arrays must be balanced");
for (int i = 0; i < pattern.Length; i++)
{
input = Regex.Replace(input, pattern[i], replacements[i]);
}
return input;
}
}
}
I put a title like: "let's say that I have --- in there what to do" but I get the same results only with the single apostrophe trimmed (let's -> lets), nothing else changed.
I want the same equivalent conversion as Wordpress'. Using ASP.NET 4.5 / C#
Since in C# you do not have action modifiers, there are no regex delimiters.
The solution is simply to remove / symbols from the pattern:
filename = Regex.Replace(filename, #"[\s-]+", "-");
^ ^
How can I convert this list of strings to comma separated value enclosed within quotes without any escape characters?
{"apple", "berry", "cherry"} => well, ""apple", "berry", "cherry""
If I understood you correctly,
"\"" + String.Join("\", \"", new string[]{"apple","berry","cherry"}) + "\"";
or, alternatively,
String.Format("\"{0}\"", String.Join("\", \"", new string[] {"apple","berry","cherry"}));
Read more on System.String.Join(...).
Hope this will do the job
var ar = new []{ "apple", "berry", "cherry" };
var separator = "\",\"";
var enclosingTag = "\"";
Console.WriteLine ( enclosingTag + String.Join(separator, ar) + enclosingTag );
If you are using C#:
using System;
string[] arr = new string[] { "apple", "berry", "cherry" };
string sep = "\",\"";
string enclosure = "\"";
string result = enclosure + String.Join(sep, arr) + enclosure;
I currently have the following code:
string user = #"DOMAIN\USER";
string[] parts = user.Split(new string[] { "\\" }, StringSplitOptions.None);
string user = parts[1] + "#" + parts[0];
Input string user can be in one of two formats:
DOMAIN\USER
DOMAIN\\USER (with a double slash)
Whats the most elegant way in C# to convert either one of these strings to:
USER#DOMAIN
Not sure you would call this most elegant:
string[] parts = user.Split(new string[] {"/"},
StringSplitOptions.RemoveEmptyEntries);
string user = string.Format("{0}#{1}", parts[1], parts[0]);
How about this:
string user = #"DOMAIN//USER";
Regex pattern = new Regex("[/]+");
var sp = pattern.Split(user);
user = sp[1] + "#" + sp[0];
Console.WriteLine(user);
A variation on Oded's answer might use Array.Reverse:
string[] parts = user.Split(new string[] {"/"},StringSplitOptions.RemoveEmptyEntries);
Array.Reverse(parts);
return String.Join("#",parts);
Alternatively, could use linq (based on here):
return user.Split(new string[] {"/"}, StringSplitOptions.RemoveEmptyEntries)
.Aggregate((current, next) => next + "#" + current);
You may try this:
String[] parts = user.Split(new String[] {#"\", #"\\"}, StringSplitOptions.RemoveEmptyEntries);
user = String.Format("{0}#{1}", parts[1], parts[0]);
For the sake of adding another option, here it is:
string user = #"DOMAIN//USER";
string result = user.Substring(0, user.IndexOf("/")) + "#" + user.Substring(user.LastIndexOf("/") + 1, user.Length - (user.LastIndexOf("/") + 1));