Find and replace content within string (C#) - c#

The below string is coming from a DIV tag. So I have enclosed the value below.
String cLocation = "'target="_blank'></a><img alt='testimage.jpg' src='/SPECIMAGE/testimage.jpg'"
I would like to replace in the above string by changing "src="/" with "src='xyz/files'".
I have tried the typical string.Replace("old","new") but it didn't work.
I tried the below,
cNewLocation ="xyz/files";
cNewString = cLocation.Replce("src='/'", "src='" + cNewLocation + "'/")
It didn't work.
Please suggest.

If I'm understanding what you're asking, you could use Regex to replace the string like so:
var cNewString = Regex.Replace(cLocation, #"src='/.*/", "src='" + newLocation + "/");
EDIT : I modified the regular expression to replace src='/.../ with src='{newLocation}/

you might try looking at the Replace command in c#.
so mystring = srcstring.Replace("old", "New");
http://msdn.microsoft.com/en-us/library/system.string.replace%28v=vs.71%29.aspx
possible replace the / in the string with //?

You can do the following:
string cLocation = "'target='_blank'></a><img alt='testimage.jpg' src='/SPECIMAGE/testimage.jpg'";
cLocation = cLocation.Replace("src='/'", "src='xyz/files'");

This fixes the problem:
int start = cLocation.IndexOf("src='") + 5;
int end = cLocation.LastIndexOf("'");
string xcLocation = cLocation.Remove(start, end - start);
string cLocation = xcLocation.Insert(start , "xyz/files");

Related

Remove part of a string between an start and end

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>

How can I insert a word at the first space in a line in c#?

I have a string like following,
string myline="public methodname(parameters)";
How can I insert a new string, like "static" at the first occurence space, that is between public and methodname.
Note that the first word and second word of my string can be anything. And I want to insert a string at the first space in my string.
so my output will be like
public static methodname(parameters)
I have used, Insert and IndexOf methods. But I cannot get the exact result. Please help. Thanks in Advance
Here you go
string myline = "public methodname(parameters)";
string result = myline.Insert(myline.IndexOf(' '), " static");
Or you can try Replace
string myline = "public methodname(parameters)";
string result = myline.Replace("public ", "public static ")
.NET Fiddle
Example:
string s = "Dot Net ";
string v = s.Replace("Net", "Basket");
Something like this, I haven't tested previous version of the code, follow should be OK.
String myline = "Public something";
int pos = myline.IndexOf(" ");
if(pos < 0)
{
//Error
}
String stringYouWant = myline.Substring(0, pos) + " static " + myline.Substring(pos +1);
Console.WriteLine(stringYouWant);

Regular Expressions to find and replace text

I have a string variable and following is the content of it:
.....
DataElement deAbtVersionNum
m_AttrParent commercialcardsys::CommercialCardInt
m_AttrGUIFieldLabel "WEX_CI 3.02.01P20.1" appsys30::lngDbb
m_AttrdbType "char"
.....
As the ... indicates, there maybe other text also.
In the third line we have "WEX_CI 3.02.01P20.1" (This is the only place starting from bottom where WEX.. is present.)
I need to replace 3.02.01P20.1(entirely) with a new version say 3.02.01P20.1.NEW
I have been able to do it using a dirty method which looks for the index of "Wex and then finds the next " and blah blah.
int start = CItext.LastIndexOf("\"WEX") + 1;
int end = CItext.IndexOf("\"", start);
string text = CItext.Substring(start, end - start + 1);
string[] parts = text.Split(new Char[] { ' ' });
string editedText = parts[0] + " " + LabelName;
CItext = CItext.Replace(text, editedText);
CIText is the string that I have to edit.
LabelName is the string I want to put instead of 3.02.01P20.1
Can anyone suggest me any other clean method ?
Try This Regex
var result = Regex.Replace(text,#"(WEX_CI[\s][\da-zA-Z\.]+)","$1.NEW");
I think you can use a regex with "lookahead". Try this.
var result = Regex.Replace(text, "(?<=WEX_CI )[^\"]+", "NEW", RegexOptions.Multiline);

Parse text from textbox

i have string in textbox:
`New-Value = 12,34 -- Old-Values: 12,31,`
what i'd like to do is to get Old-Value so "12,31,"
How can i get from this textbox this specific information do this? So value is between ":" and ","
Tnx
Regex.Match("New-Value = 12,34 -- Old-Values: 12,31,",#"\:(.+)\,").Groups[1].Value.Trim()
const string oldPointer = "Old-Values: ";
var text = "New-Value = 12,34 -- Old-Values: 12,31,";
var old = text.Substring(text.IndexOf(oldPointer) + oldPointer.Length).TrimEnd(',');
Not very clear if this is a fixed (static) format of your string, but by the way:
A simple solution could be:
string str = "New-Value = 12,34 -- Old-Values: 12,31,";
str.Substring(str.IndexOf(':') + 1);
More complex one should involve Regular expressions, like an answer of L.B or others if any.

How to split the two strings using filetype.split?

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");

Categories