Below I have two regex's that operate on some text:
assume key = "old" and value = "new"
text = Regex.Replace(text,
"\\." + change.Key + ",",
"." + change.Value + ","
);
text = Regex.Replace(text,
"\\." + change.Key + ";",
"." + change.Value + ";"
);
So, ".old," and ".old;" would change to ".new," and ".new;", respectively.
I'm sure this could be shortened to one regex. How can I do this so that the string only changes when the comma and semicolon are at the end of the variable? For example, I don't want ".oldQ" to change to ".newQ". Thanks!
.NET uses $ for backreferences:
text = Regex.Replace(text,
#"\." + change.Key + "([,;])",
"." + change.Value + "$1");
Out of my head:
text = Regex.Replace(text, #"\.(old|new),",#"\.\1;");
You want to just change the middle part, so:
text = Regex.Replace(text,
"\\." + change.Key + "(,|;)^", // mark a group using "()" for substitution...
"." + change.Value + "\1" // use the group ("\1")
);
I like using \b, like this:
text = Regex.Replace(text, #"\." + change.Key + #"\b", "." + change.Value);
It would match on keywords followed by other delimiters, not just "," and ";", but it may still work in your case.
Related
I am trying to write a continues line in CSV.
Using one line of code it would look like that:
outputFile.WriteLine("1111" + "," + "2222" + "," + "3333" + "," + "4444" + "," + "5555" + "," + "6666");
well the line is too long for me and I want to split it into two or more lines of code.
I have tried this:
outputFile.WriteLine("1111" + "," + "2222" + "," + "3333" + "," + "4444");
outputFile.WriteLine("," + "5555" + "," + "6666");
But the end resulte is two lines in the CSV file with an empty cell in the second line.
You can use StringBuilder like this:
StringBuilder line = new StringBuilder();
line.Append("1111");
line.Append(",");
line.Append("2222");
//..
outputFile.WriteLine(line.ToString());
I am trying to pass quotes in string. I am having a hard time formulating the code.
path = path.Insert(0, #"\\ffusvintranet02\picfiles\temp\");
string format = "Set-UserPhoto ";
format += "" + user + "";
format += " -PictureData ([System.IO.File]::ReadAllBytes(";
format += "" + path + #"";
format += ")";
The user and path are variables that needs to be inside single quotes for the AD Command. command. What I have isn't working.
User \" for " symbol or \' for '
format += "\"" + user + "\"";
First of all , use string.format for such tasks. Second you have to escape quotes ( but you dont need to escape single quotes).
Double quotes can be escaped by double quote or by backslash based on type of string literal you are using:
var s = #"something "" somethin else "; // double double quote here
var s2 = "something \" somethin else ";
Now, using string.format, your code will turn into:
path = path.Insert(0, #"\\ffusvintranet02\picfiles\temp\");
string format = string.format("Set-UserPhoto {0} -PictureData ([System.IO.File]::ReadAllBytes(\"{1}\")", user, path);
or
path = path.Insert(0, #"\\ffusvintranet02\picfiles\temp\");
string format = string.format(#"Set-UserPhoto {0} -PictureData ([System.IO.File]::ReadAllBytes(""{1}"")", user, path);
string format = "Set-UserPhoto "; format += "'" + user + "'"; format += " -PictureData ([System.IO.File]::ReadAllBytes("; format += "'" + path + #"'"; format += ")";
I would suggest using string interpolation within a here-string as follows, this will prevent you from having to use string concatenation and escaping.
$format = #"
Set-UserPhoto " + user + " -PictureData ([System.IO.File]::ReadAllBytes(" + path + ")"
"#
I am trying to get a snippet of HTML between to comments.
I will need to parse the HTML between the start/end later.
I am actually reading from an html file but for test purposes I mocked the following up:
string emailFeedTxtStart = "<!--FEED FOR RECEIPT GOES HERE-->";
string emailFeedTxtEnd = "<!--FEED FOR RECEIPT ENDS HERE-->";
string html =
emailFeedTxtStart + Environment.NewLine +
#"<td align=""center"">" + Environment.NewLine +
#"<table style=""table-layout:fixed;width:380px"" border=""0"" cellspacing=""0"" cellpadding=""0"">" + Environment.NewLine +
"<tbody>" + Environment.NewLine +
"<tr>" + Environment.NewLine +
"<td>" + Environment.NewLine +
"</td>" + Environment.NewLine +
"</tr>" + Environment.NewLine +
"</tbody>" + Environment.NewLine +
"</table>" + Environment.NewLine +
"</td>" + Environment.NewLine +
emailFeedTxtEnd;
string patternstart = Regex.Escape(emailFeedTxtStart);
string patternend = Regex.Escape(emailFeedTxtEnd);
string regexexpr = patternstart + #"(.*?)" + patternend;
//string regexexpr = #"(?<=" + patternstart + ")(.*?)(?=" + patternend + ")";
MatchCollection matches = Regex.Matches(#html, #regexexpr);
matches returned is 0.
(note there is a lot more HTML between the ).
Any help would be greatly appreciated.
What are you going to parse the HTML with after? Because there's probably a way you can just do away with actually manipulating the HTML string beforehand. Here's a solution anyway:
string afterFirst = html.Substring(Regex.Match(html, emailFeedTxtStart).Index + emailFeedTxtStart.Length);
string between = afterFirst.Substring(0, Regex.Match(afterFirst, emailFeedTxtEnd).Index);
I have taken my regex from python and try to make work in c#, while i get no errors, it does not display any output and during debug, i do not see the output varible get populated with any data, here is snippet:
StringWriter strwriter = new StringWriter();
rule = sr.ReadLine();
do
{
Regex action = new Regex(#"^#\w+(?<action>(alert)\\s+(tcp|udp)\\s+(.*?)\\('*}))");
Regex message = new Regex("(?<msg>[\\s(]*\\((.*)\\)[^)]*$)", RegexOptions.IgnorePatternWhitespace);
Regex content = new Regex("(?<content>[\\s(]*\\((.*)\\)[^)]*$)", RegexOptions.IgnorePatternWhitespace);
Match result = action.Match(rule);
//String repl = Regex.Replace(rule, "[\\;]", ",");
//Match mat = action.Match(repl);
Console.WriteLine(result.Groups["action"].Value);
//writer.WriteLine(result.Groups["action"].Value + "," + result.Groups["msg"].Value + "," + result.Groups["content"].Value + "," + result.Groups["flow"].Value + "," + result.Groups["ct"].Value + "," + result.Groups["pcre"].Value + "," + result.Groups["sid"].Value);
} while (rule != null);
result does not show anything, what have i missed, these are almost the same one that i have working in the python script.
Since you're using string literals for the first regex, don't double escape!
^#\w+(?<action>(alert)\\s+(tcp|udp)\\s+(.*?)\\('*}))
^ ^ ^
=>
^#\w+(?<action>(alert)\s+(tcp|udp)\s+(.*?)\('*}))
With the input, there were a couple of more things wrong with the regex and this one should bring you in the right direction:
^#\s*(?<action>alert\s+(?:tcp|udp)\s+(.*?)\([^)]*\))
regex101 demo
If you don't want the part within parentheses, you can omit the last part:
^#\s*(?<action>alert\s+(?:tcp|udp)\s+(.*?)\()
I need to replace the characters ; and linebreak to the field p.notas. I tried this but it doesn't replace the linebreaks.
var res = from p in miDataContext.clientes
orderby p.nombreCom
select
(p.nombreCom ?? "") + ";" +
(p.razon ?? "") + ";" +
(p.nif ?? "") + ";" +
((p.notas ?? "").Replace (";" ,"."))
.Replace(Environment.NewLine , ". ");
The problem with using Environment.NewLine in your Replace() call is that the newline character(s) in your environment my not necessarily match what is actually used in the string. Yours probably has \r\n (windows) but what is actually stored is just \n. That pattern is definitely not in the string in that case. You'll have to check for all newline variants.
Assuming this is all fine in LINQ to SQL, just add more replace calls for each of the newline types.
var res = from p in miDataContext.clientes
orderby p.nombreCom
select
(p.nombreCom ?? "") + ";" +
(p.razon ?? "") + ";" +
(p.nif ?? "") + ";" +
((p.notas ?? "").Replace(";", "."))
.Replace("\r\n", ". ")
.Replace("\n", ". ")
.Replace("\r", ". ");