This seems really simple, but I have a string that I want to replace a string with a tab and 2 new lines and it isn't working.
string newString = "\tMyVariable : Bool\n\t\nEND_VAR";
string pattern = "\n\t\nEND_VAR";
string original = "VAR_GLOBAL\n\t\nEND_VAR\n";
string updatedString = Regex.Replace(original,pattern,newString);
updatedString never gets updated, it remains at "VAR_GLOBAL\n\t\nEND_VAR\n", where it should be "VAR_GLOBAL\tMyVariable : Bool\n\t\nEND_VAR\n". I'm not sure why it won't change.
While Regex might not be the best suited for such scenario, please find below a sample code which will suit your needs (Regex test).
string newString = "\tMyVariable : Bool\n\t\nEND_VAR";
string pattern = "\\n\\t\\nEND_VAR";
string original = "VAR_GLOBAL\n\t\nEND_VAR\n";
string updatedString = Regex.Replace(original,pattern,newString);
The other (maybe simplier) option would be to do a straight replace like in:
string newString = "\tMyVariable : Bool\n\t\nEND_VAR";
string updatedString = newString.Replace("\n\t\n", "\t");
Related
So I have this string which I have to trim and manipulate a little with it.
My string example:
string test = "studentName_123.pdf";
Now, what I want to do is somehow extract only the _123 part and at the end I need to have studentName.pdf
What I have tried:
string test_extracted = test.Substring(0, test.LastIndexOf("_") )+".pdf";
This also works but the thing is that I don't want to add the ".pdf" suffix at the end of the string manually because I can have strings that are not pdf, for ex. studentName.docx , studentName.png.
So basically I just want the "_123" part removed but still keep the remain part after that.
I think this might help you:
string test = "studentName_123.pdf";
string test_extracted = test.Substring(0, test.LastIndexOf("_") )+ test.Substring(test.LastIndexOf("."),test.Length - test.LastIndexOf(".") );
Using Remove(int startIndex, int count):
string test = "studentName_123.pdf";
string test_extracted = test.Remove(test.LastIndexOf("_"), test.LastIndexOf(".") - test.LastIndexOf("_"));
Sounds like you mean something like this?
string extension = Path.GetExtension(test);
string pdfName = Path.GetFileNameWithoutExtension(test).Split('_')[0];
string fullName = pdfName + extension;
Since you know what value you will always be replacing in your strings, "_123", to base on your example, just utilize the replace method and replace it with nothing since the method expects two arguments;
string test_extracted = test.replace('_123', '');
This could be solved with a regular expression like this
(\w*)_.*(\.\w*) where the first capture group (\w*) matches everything before the underscore and the second group (\.\w*) matches the file extensions.
Lastly we just have to concat the groups without the stuff inbetween like so:
string test = "studentName_123.pdf";
var regex = Regex.Match(test, #"(\w*)_.*(\.\w*)");
string newString = regex.Groups[1].Value + regex.Groups[2].Value;
I would appreciate some help on this, I am currently working on a item, the SAP CL Invoice Number is coming from CRM for example CL00131713, on my HTML view it is getting correctly mapped, however the requirement states there should be a - in the SAP CL Invoice Number. This should show as CL-00131713 like the image below:
My code is in my model.cs
public string SAPCLInvoiceNumber { get; set; }
In my organisation.cs class
result.Add(new InvoiceModel
{
SAPCLInvoiceNumber = invoice.SAPCLInvoiceNumber,
});.
Finally in my HTML I do
<tr ng-repeat="invoice in vm.invoices">
<td>
<!-- {{invoice.Number}} -->
{{invoice.SAPCLInvoiceNumber}}
</td>
I believe I need to do something like
SAPCLInvoiceNumber = string.replace("CL","CL - " + string.replace("CL", SAPCLInvoiceNumber ))
Please advise
Something like this should do the trick :
string pattern = #"CL";
string substitution = #"CL-";
string input = #"CL00131713";
Regex regex = new Regex(pattern);
string result = regex.Replace(input, substitution);
You can create an extension function to simplify the call
public static string FormatClNumber(this string cl)
{
string pattern = #"CL";
string substitution = #"CL-";
string input = cl;
Regex regex = new Regex(pattern);
return regex.Replace(input, substitution);
}
You can insert a "-" after second char if it is not there. Its a very simple and efficient code:
string s = "CL00131713"; //SAPCLInvoiceNumber
if (s != null & s.Length > 2 && s[2] != '-') s = s.Insert(2, "-");
I think this is better and more complete solution (eg. check if the string does not already contain the dash char, otherwise if you call it twice o a given value you will damage it to something like "CL--00131713").
Imagine I have a string like:
xxxstrvvv string xxxstringvvv str I am string for testing.
I want to find and replace all instances of str with xxxstrvvv that are not already contained in a xxxvvv.
so the result would be:
xxxstrvvv xxxstrvvving xxxstringvvv xxxstrvvv I am xxxstrvvving for testing
Anyone know an easy way to do this?
Edit: I want to add another situation to clarify.
xxxabcstrefgvvv
it should NOT replace this because the str is contained in xxxvvv
I suggest using regular expression with negative looking ahead and behind:
string source = "xxxstrvvv string xxxstringvvv str I am string for testing.";
string result = Regex.Replace(source, #"(?<!xxx)str(?!vvv)", "xxxstrvvv");
Edit: Same method, but a bit different pattern for the edited question:
string result = Regex.Replace(
source,
#"(?<!xxx[a-zA-Z]*)str(?![a-zA-Z]*vvv)", "xxxstrvvv");
Outcomes:
source = "xxxstrvvv string xxxstringvvv str I am string for testing.":
xxxstrvvv xxxstrvvving xxxstringvvv xxxstrvvv I am xxxstrvvving for testing.
source = "xxxabcstrefgvvv":
xxxabcstrefgvvv
Ok, I agreed with the answer of Dmitry Bychenko about Regular Expressions.
But, if your request is limited to the requirement on your answer we can use this code:
string val = "xxxstrvvv string xxxstringvvv str I am string for testing.";
val = val.Replace("xxxstringvvv", "str");
val = val.Replace("str","xxxstringvvv");
I'd go with the regex, but if you want to use replaces, this would work, if you don't have "xxxxxxstrvvvvvv" in your initial string and want to keep them that way:
string findString = "str";
string addBefore = "xxx";
string addAfter = "xxx";
string myString = "xxxstrvvv string xxxstringvvv str I am string for testing.";
myString = myString.Replace(findString, addBefore+findString+addAfter);
myString = myString.Replace(addBefore+addBefore+findString+addAfter+addAfter, addBefore+findString+addAfter);
Yes; it is ugly. I just basically do that in Notepad++ all the time with ctrl-H.
I have written a script in Python. I think you would be able to convert it to C#.
one_line = 'xxxstrvvv string xxxstringvvv str I am string for testing'
final_str = ""
arry_len = one_line.split(" ")
for ch in arry_len:
if 'str' in ch:
if not 'xxxstrvvv' in ch:
ch = ch.replace("str","xxxstrvvv")
final_str = final_str + " " + ch
print final_str
I tried to split a string wich contains these character #
domicilioSeparado = domicilio.Split(#"#".ToCharArray());
but every time the array contains just one member. I've tried a lot of combinations but anything seems to work, I also tried to replace the string with a blank space and it kinda works - the problem is that it remains a single string.
domicilio = domicilio.Replace(#"#", #" ");
How can I resolve this?
Complete code:
String[] domicilioSeparado;
String domicilio = dbRow["DOMICILIO"].ToString();
domicilioSeparado = domicilio.Split(#"#".ToCharArray());
if (Regex.IsMatch(domicilioSeparado.Last(), #"\d"))
{
String domicilioSinNum = "";
domicilioSinNum = domicilioSeparado[0];
custTable.Rows.Add(counter, dbRow["CUENTA"], nombre,
paterno, materno, domicilioSinNum, domicilioSeparado.Last(), tipoEntidad);
}
If you just want to split a string on a delimiter, in this instance '#', then you can use this:
domicilioSeparado = domicilio.Split("#");
That should give you what you want. Your second attempt simply replaces all the characters '#' in the string with ' ', which doesn't seem to be what you want. Can we see the string you're trying to split? That might help explain why it's not working.
EDIT:
Ok, here's how I think your code should look, give this a shot and let me know how it goes.
List<string> domicilioSeparado = new List<string>();
String domicilio = dbRow["DOMICILIO"].ToString();
domicilioSeparado = domicilio.Split("#");
if (Regex.IsMatch(domicilioSeparado.Last(), #"\d"))
{
String domicilioSinNum = "";
domicilioSinNum = domicilioSeparado[0];
custTable.Rows.Add(counter, dbRow["CUENTA"], nombre,
paterno, materno, domicilioSinNum, domicilioSeparado.Last(), tipoEntidad);
}
Try this:
string[] domicilioSeparado;
domicilioSeparado = domicilio.Split('#');
Some notes:
1 - It is ('#'), instead of ("#"); 2 - Replace does not split a string, it only replace that part, keeping as a single string.
In case you want an example that includes the printing of the whole array:
string domicilio = "abc#def#ghi";
string[] domicilioSeparado;
domicilioSeparado = domicilio.Split('#');
for (int i = 0; i < domicilioSeparado.Length; i++)
{
MessageBox.Show(domicilioSeparado[i]);
}
It will open a Message Box for each element within domicilioSeparado.
I want to replace a charecter in a string with a string in c#.
I have tried the following,
Here in the following program, i want replace set of charecters between charecters ':' and first occurance of '-' with some others charecters.
I could able to extract the set of charecters between ':' and first occurance of '-'.
Can any one say how to insert these back in the source string.
string source= "tcm:7-426-8";
string target= "tcm:10-15-2";
int fistunderscore = target.IndexOf("-");
string temp = target.Substring(4, fistunderscore-4);
Response.Write("<BR>"+"temp1:" + temp + "<BR>");
Examples:
source: "tcm:7-426-8" or "tcm:100-426-8" or "tcm:10-426-8"
Target: "tcm:10-15-2" or "tcm:5-15-2" or "tcm:100-15-2"
output: "tcm:10-426-8" or "tcm:5-426-8" or "tcm:100-426-8"
In a nutshell, I want to replace the set of charectes between ':' and '-'(firstoccurance) and the charecters extracetd from the same sort of string.
Can any help how it can be done.
Thank you.
If you want to replace the first ":Number-" from the source with the content from target, you can use the following regex.
var pattern1 = New Regex(":\d{1,3}-{1}");
if(pattern1.IsMatch(source) && pattern1.IsMatch(target))
{
var source = "tcm:7-426-8";
var target = "tcm:10-15-2";
var res = pattern1.Replace(source, pattern1.Match(target).Value);
// "tcm:10-426-8"
}
Edit: To not have your string replaced with something empty, add an if-clause before the actualy replacing.
Try a regex solution - first this method, takes the source and target strings, and performs a regex replace on the first, targetting the first numbers after the 'tcm', which must be anchored to the start of the string. In the MatchEvaluator it executes the same regex again, but on the target string.
static Regex rx = new Regex("(?<=^tcm:)[0-9]+", RegexOptions.Compiled);
public string ReplaceOneWith(string source, string target)
{
return rx.Replace(source, new MatchEvaluator((Match m) =>
{
var targetMatch = rx.Match(target);
if (targetMatch.Success)
return targetMatch.Value;
return m.Value; //don't replace if no match
}));
}
Note that no replacement is performed if the regex doesn't return a match on the target string.
Now run this test (probably need to copy the above into the test class):
[TestMethod]
public void SO9973554()
{
Assert.AreEqual("tcm:10-426-8", ReplaceOneWith("tcm:7-426-8", "tcm:10-15-2"));
Assert.AreEqual("tcm:5-426-8", ReplaceOneWith("tcm:100-426-8", "tcm:5-15-2"));
Assert.AreEqual("tcm:100-426-8", ReplaceOneWith("tcm:10-426-8", "tcm:100-15-2"));
}
I'm not clear on the logic used to decide which bit from which string is used, but still, you should use Split(), rather than mucking about with string offsets:
(note that the Remove(0,4) is there to remove the tcm: prefix)
string[] source = "tcm:90-2-10".Remove(0,4).Split('-');
string[] target = "tcm:42-23-17".Remove(0,4).Split('-');
Now you have the numbers from both source and target in easy-to-access arrays, so you can build the new string any way you want:
string output = string.Format("tcm:{0}-{1}-{2}", source[0], target[1], source[2]);
Heres without regex
string source = "tcm:7-426-8";
string target = "tcm:10-15-2";
int targetBeginning = target.IndexOf("-");
int sourceBeginning = source.IndexOf("-");
string temp = target.Substring(0, targetBeginning);//tcm:10
string result = temp + source.Substring(sourceBeginning, source.Length-sourceBeginning); //tcm:10 + -426-8