C # Replace part of string
How to replace a part of a string with a potentially unknown starting index. For example, if I had the following lines:
"<sometexthere width='200'>"
"<sometexthere tile='test' width='345'>"
I would like to replace the attibute width, which may have an unknown value and, as stated above, to an unknown starting index.
I understand that I will somehow have to base this on the next part which is constant, I just don't quite understand how to achieve this.
width='
source to share
So far, you have seven answers telling you to do the wrong thing. Don't use regular expressions to execute the parser. I am assuming your line is a piece of markup. Let's assume it's HTML. What does your regex do with:
<html>
<script>
var width='100';
</script>
<blah width =
'200'>
... and so on ...
I would bet just like the dollar that it replaces the JScript code, which it shouldn't, and does not replace the blah tag attribute - it is perfectly legal to have a space in the attribute.
If you need to parse the markup language then parse the markup language . Get a parser and use it; what parsers are for.
source to share
Take a look at the Regex class , you can search for attribute content and return value using this class.
Disable cuff Regex.Replace can do the trick:
var newString = Regex.Replace(@".*width='\d'",string.Foramt("width='{0}'",newValue));
source to share
Use regex
Regex regex = new Regex(@"\b(width)\b\s*=\s*'d+'");
where \b
indicates that you want to match an entire word, \s*
allows zero or any number of whitespace characters, and \d+
allows one or more numeric placeholders. To replace a numeric value, you can use:
int nRepValue = 400;
string strYourXML = "<sometexthere width='200'>";
// Does the string contain the width?
string strNewString = String.Empty;
Match match = regex.Match(strYourXML);
if (match.Success)
strNewString =
regex.Replace(strYourXML, String.Format("match='{0}'", nRepValue.ToString()));
else
// Do something else...
Hope it helps.
source to share
To achieve this, use regular expressions:
using System.Text.RegularExpressions;
...
string yourString = "<sometexthere width='200'>";
// updates width value to 300
yourString = Regex.Replace(yourString , "width='[^']+'", width='300');
// replaces width value with height value of 450
yourString = Regex.Replace(yourString , "width='[^']+'", height='450');
source to share
I would use Regex .
Something like this to replace the width value with 123456
.
string aString = "<sometexthere tile='test' width='345'>";
Regex regex = new Regex("(?<part1>.*width=')(?<part2>\\d+)(?<part3>'.*)");
var replacedString = regex.Replace(aString, "${part1}123456${part3}");
source to share