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
Related
Code first:
string myString = "<at>onePossibleName</at> some question here regarding <at>disPossibleName</at>"
// some code to handle myString and save it in myEditedString
Console.WriteLine(myEditedString);
//output now is: some question here regarding <at>disPossibleName</at>
I want to remove <at>onePossibleName</at> from myString. The string onePossibleName and disPossbileName could be any other string.
So far I am working with
string myEditedString = string.Join(" ", myString.Split(' ').Skip(1));
The problem here would be that if onePossibleName becomes one Possible Name.
Same goes for the try with myString.Remove(startIndex, count) - this is not the solution.
There will be different method depending on what you want, you can go with a IndexOf and a SubString, regex would be a solution too.
// SubString and IndexOf method
// Usefull if you don't care of the word in the at tag, and you want to remove the first at tag
if (myString.Contains("</at>"))
{
var myEditedString = myString.Substring(myString.IndexOf("</at>") + 5);
}
// Regex method
var stringToRemove = "onePossibleName";
var rgx = new Regex($"<at>{stringToRemove}</at>");
var myEditedString = rgx.Replace(myString, string.Empty, 1); // The 1 precise that only the first occurrence will be replaced
You could use this generic regular expression.
var myString = "<at>onePossibleName</at> some question here regarding <at>disPossibleName</at>";
var rg = new Regex(#"<at>(.*?)<\/at>");
var result = rg.Replace(myString, "").Trim();
This would remove all 'at' tags and the content between. The Trim() call is to remove any white space at the beginning/end of the string after the replacement.
string myString = "<at>onePossibleName</at> some question here regarding <at>disPossibleName</at>"
int sFrom = myString.IndexOf("<at>") + "<at>".Length;
int sTo = myString.IndexOf("</at>");
string myEditedString = myString.SubString(sFrom, sFrom - sTo);
Console.WriteLine(myEditedString);
//output now is: some question here regarding <at>disPossibleName</at>
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");
I want to search a long string for a string inside it that BeginsWith and EndsWith something, and then eventually replace it with a token.
So, let's say I have a string:
"This is text with a token: <TokenID=123>doesn't matter</Token>, and some more text!"
I'd like to extract/identify the following string:
<TokenID=123>doesn't matter</Token>
So that I can use it within a replace statement on the original string, to replace it with something else. The ID for this tag could be different, so I want to identify the string above by using something like:
var beginsWith = "<TokenID=";
var endsWith = "</Token>";
The BeginsWith and EndsWith values will be pulled from a CSV file into a list, as there are many of them with different content. Once I know how to extract these, I eventually want to replace them with a character that I could split on to create an array of strings around the extracted strings.
I don't want to use regex, as the BeginsWith and EndsWith strings need to be easily configurable and added to at a later stage.
This feels like it should be a really simple exercise, but for the life of me I can't figure out how to do it...
If I'm understanding your question correctly, you're going to want to use IndexOf() & Substring().
IndexOf() will get you the locations of your beginsWith and endWith for which you can provide to the Substring()
string data = "This is text with a token: <TokenID=123>doesn't matter</Token>, and some more text!";
string beginsWith = "<TokenID=";
string endsWith = "</Token>";
int startIndex = data.IndexOf(beginsWith);
// Add the length of endWidth so you're getting the location of the last character of the endsWith
int endIndex = data.IndexOf(endsWith) + endsWith.Length;
string extract = data.Substring(startIndex, endIndex - startIndex);
Console.WriteLine(extract);
Console.ReadLine();
Results:
<TokenID=123>doesn't matter</Token>
If you change your mind about using Regex, you can still use your beginsWith and endsWith to create your pattern.
string data = "This is text with a token: <TokenID=123>doesn't matter</Token>, and some more text!";
string beginsWith = "<TokenID=";
string endsWith = "</Token>";
string extract = Regex.Match(data, String.Format("{0}.+{1}", beginsWith, endsWith)).Value;
Console.WriteLine(extract);
Console.ReadLine();
The String.Format() creates a pattern that looks like
<TokenID=.+</Token>
Results:
<TokenID=123>doesn't matter</Token>
Here's an extension method so you can just attach it to a string:
Method
private static string StringBetween( this string StringEval, string startsWith, string endsWith)
{
var str = StringEval;
var start = str.IndexOf(startsWith);
var end = str.IndexOf(endsWith, start);
var val = str.Substring(start, (end - start) + endsWith.Length);
return val;
}
Usage
static void Main(string[] args)
{
var exampleStr = "This is text with a token: <TokenID=123>doesn't matter</Token>, and some more text!";
var startsWith = "<TokenID=";
var endsWith = "</Token>";
var val = exampleStr.StringBetween(startsWith, endsWith);
Console.WriteLine(val);
Console.ReadKey();
}
Without using Regex:
string s="This is text with a token: <TokenID=123>doesn't matter</Token>, and and some more text!"
string beginsWith = "<TokenID=";
string endsWith = "</Token>";
string Extract = null ;
int i,j ;
if ((i=s.IndexOf(beginsWith))>=0) && ((j=s.Substring(i).IndexOf(endsWith)>=0))
Extract=s.Substring(i,j)+endsWith ;
// result in extract (null if delimiting strings not found)
I have strings that all have different lengths.
e.g.
str1 = "This is new job ----First Message----- This is reopened ";
str2 = "Start Process ----First Message----- Is this process closed? <br/> no ----First Message-----";
Now these string shall always have the "----First Message-----" in it.
What I need is to trim or split the string in such a way that I only get the part left of the FIRST TIME the "----First Message-----" occurs.
So in case of str1 result should be "This is new job "
For str2 it should be "Start Process "
How can this be done in C#?
string stringStart = str1.Substring(0, str1.IndexOf("----First Message-----"));
String result = input.Substring(0, input.IndexOf('---FirstMessage-----'));
actually, for teaching purposes...
private String GetTextUpToFirstMessage( String input ){
const string token = "---FirstMessage-----";
return input.Substring(0, input.IndexOf(token));
}
This sounds like a job for REGULAR EXPRESSIONS!!!!
try the following code. don't forget to include the using System.Text.RegularExpressions; statement at the top.
Regex regex = new Regex(#"^(.*)----FirstMessage----$");
string myString = regex.Match(str1).Value;
I have got a string as follows:
string name ="C:\folder\back-201190082233.zip";
How can I get only the part 201190082233 from the string name? I have tried like this for getting the only the part 201190082233
string filetype = name;
string[] getfiledate = filetype.Split('-');
But I am getting the part 201190082233.zip. Now I want to get only the part 201190082233. Would anyone please help on this?
Seems like a good idea to use regular expressions:
var match = Regex.Match("back.201190082233.zip" , #"(?<=-)\d+(?=\.)");
if(match.Success)
{
var numericPart = match.Value;
}
Edit:
If you're dealing with paths, .Net offers help:
string name = #"C:\folder\back.201190082233.zip";
var fileName = Path.GetFileName(name);
var match = Regex.Match(fileName , #"(?<=-)\d+(?=\.)");
if(match.Success)
{
var numericPart = match.Value;
}
string name = "C:\folder\back-201190082233.zip";
string filetype = name;
string[] getfiledate = filetype.Split(new[] {'.', '-'});
string datepart = getfiledate[1];
How about this way?
var fileDate= filetype.Split('.')[1];
Edit for updates
var fileDate = Path.GetFileNameWithoutExtension(filetype).Split('.')[0]
Probably
var date = Path.GetFileNameWithoutExtension( name ).Split('-')[1];
would be sufficient.
See documentation for function Path.GetFileNameWithoutExtension.
Why are you splitting with a '-' ? Shouldn't it be '.' ?
string numberPart = filetype.Split('.')[1];
You may use something like below
string str = name.Split(".")[1];
Hope this helps!!
or if the string changes you could use a mor specific regular expression like this:
string s = Regex.Replace("back.201190082233.zip", #"[^\.]+\.([^\.]+)\..*", "$1");