Replace substring in stringbuilder, don't know location of substring - c#

Example: If the display name contains "Lambda (?)" then replace with "Lambda (&#955").
I have four various substrings that I'm trying to replace
Here's the part of my stringbuilder code:
sb.Append("<div><a href=\"" + item.URLAliasName + "\" >" + (string.IsNullOrEmpty(item.DisplayName) ? " " : item.DisplayName) + "</a>"...
How do I replace "Lambda (?)" if contained inside item.DisplayName? It may be found anywhere in the display name.

Perhaps something like this would work?
item.DisplayName.Replace("Lambda (?)", "Lambda (&#955)");

You can use String.Replace it takes in two strings as parameters, the value to replace and what to replace it with. It returns the resulting string.
For example: String replacedString = String.Replace("Lambda(?)", "Lambda(&#955");

Related

Why this function for finding the n-th occurrence does not work on text with line breaks?

I found the following code to find the n-th occurrence of a value in a text here.
This is the code:
public static int NthIndexOf(this string target, string value, int n)
{
Match m = Regex.Match(target, "((" + value + ").*?){" + n + "}");
if (m.Success)
return m.Groups[2].Captures[n - 1].Index;
else
return -1;
}
I tried to find the index of the second occurrence of "< /form>" (the space does not appear in the original string) in some webpage, and it failed, although for sure it exists in the text. I also cut some prefix of the webpage, so the second occurrence will be the first, and then I succeeded to find the expression as the first occurrence.
In one of the comment on this code, someone wrote that "This Regex does not work if the target string contains linebreaks.".
My two questions are:
Why does not this code work if the target string contains linebreaks?
How can I fix this code, so it will work also for strings that contain linebreaks (replacing/removing the linebreaks is not considered a good solution for me)?
I don't look for other techniques to do the same thing.
the regex match till the end of the line.
For what you want you need to use the Singleline mode, so your code should look something like this:
Match m = Regex.Match(target, "((" + value + ").*?){" + n + "}", RegexOptions.Singleline);
By default Regular Expression end on a new line. To fix it you need to specify the regex option
Match m = Regex.Match(target, "((" + value + ").*?){" + n + "}", RegexOptions.MultiLine);
You can find more information about RegExOptions here.

Add file extension to variable

I am new to c sharp
can anybody say what the mistake
string cPict= "Picture\"+firstSelectedItem+".jpg";
where
"Picture\" = folder
firstSelectedItem = Employee Number
".jpg" = file extension
getting following error
string does not contain definition for jpg
please help
thanks in advance
The problem is that in "\"+firstSelectedItem all is treated as string, even the firstSelectedItem variable because you've used the \-character to escape the following ".
You either have to
escape the \-character by another one,
use a verbatim string literal or
use the Path-class, especially Path.Combine:
1)
string cPict = "Picture\\" + firstSelectedItem + ".jpg";
2)
string cPict = #"Picture\" + firstSelectedItem + ".jpg";
3)
string cPict = Path.Combine("Picture", firstSelectedItem + ".jpg");
You can replace it with normal slash like that:
string cPict= "Picture/"+firstSelectedItem+".jpg";
The \ is a special character that escapes the next character in a string, therefore, according to the compiler then + firstSelectedItem + is still part of the string. Your code should look like one of the following:
string cPict = #"Picture\" +
or:
string cPict = "Picture\\" +
and that should work.
you need to escape the backslash \ character
string cPict= "Picture\\"+firstSelectedItem+".jpg";
learn about Escape Sequences here
The solution is to add double slashes as below:
string cPict= "Picture\\"+firstSelectedItem+".jpg";
"Picture\\"=folder

Regular Expression without braces

i have the following sample cases :
1) "Sample"
2) "[10,25]"
I want to form a(only one) regular expression pattern, to which the above examples are passed returns me "Sample" and "10,25".
Note: Input strings do not include Quotes.
I came up with the following expression (?<=\[)(.*?)(?=\]), this satisfies the second case and retreives me only "10,25" but when the first case is matched it returns me blank. I want "Sample" to be returned? can anyone help me.
C#.
here you go, a small regex using a positive lookbehind, sometime these are very handy
Regex
(?<=^|\[)([\w,]+)
Test string
Sample
[10,25]
Result
MATCH 1
[0-6] Sample
MATCH 2
[8-13] 10,25
try at regex101.com
if " is included in your original string, use this regex, this will look for " mark as well, you may choose to remove ^| from lookup if " mark is always included or you may choose to leave it as it is if your text has combination of with and without " marks
Regex
(?<=^|\[|\")([\w,]+)
try at regex101.com
As far as I can tell, the below regex should help:
Regex regex = new Regex(#"^\w+|[[](\w)+\,(\w)+[]]$");
This will match multiple words, or 2 words (alphanumeric) separated by commas and inside square brackets.
One Java example:
// String input = "Sample";
String input = "[10,25]";
String text = "[^,\\[\\]]+";
Pattern pMod = Pattern.compile("(" + text + ")|(?>\\[(" + text + "," + text + ")\\])");
Matcher mMod = pMod.matcher(input);
while (mMod.find()) {
if(mMod.group(1) != null) {
System.out.println(mMod.group(1));
}
if(mMod.group(2)!=null) {
System.out.println(mMod.group(2));
}
}
if input is "[hello&bye,25|35]", then the output is hello&bye,25|35

Regex pattern for text between 2 strings

I am trying to extract all of the text (shown as xxxx) in the follow pattern:
Session["xxxx"]
using c#
This may be Request.Querystring["xxxx"] so I am trying to build the expression dynamically. When I do so, I get all sorts of problems about unescaped charecters or no matches :(
an example might be:
string patternstart = "Session[";
string patternend = "]";
string regexexpr = #"\\" + patternstart + #"(.*?)\\" + patternend ;
string sText = "Text to be searched containing Session[\"xxxx\"] the result would be xxxx";
MatchCollection matches = Regex.Matches(sText, #regexexpr);
Can anyone help with this as I am stumped (as I always seem to be with RegEx :) )
With some little modifications to your code.
string patternstart = Regex.Escape("Session[");
string patternend = Regex.Escape("]");
string regexexpr = patternstart + #"(.*?)" + patternend;
The pattern you construct in your example looks something like this:
\\Session[(.*?)\\]
There are a couple of problems with this. First it assumes the string starts with a literal backslash, second, it wraps the entire (.*?) in a character class, that means it will match any single open parenthesis, period, asterisk, question mark, close parenthesis or backslash. You'd need to escape the the brackets in your pattern, if you want to match a literal [.
You could use a pattern like this:
Session\[(.*?)]
For example:
string regexexpr = #"Session\[(.*?)]";
string sText = "Text to be searched containing Session[\"xxxx\"] the result would be xxxx";
MatchCollection matches = Regex.Matches(sText, #regexexpr);
Console.WriteLine(matches[0].Groups[1].Value); // "xxxx"
The characters [ and ] have a special meaning with regular expressions - they define a group where one of the contained characters must match. To work around this, simply 'escape' them with a leading \ character:
string patternstart = "Session\[";
string patternend = "\]";
An example "final string" could then be:
Session\["(.*)"\]
However, you could easily write your RegEx to handle Session, Querystring, etc automatically if you require (without also matching every other array you throw at it), and avoid having to build up the string in the first place:
(Querystring|Session|Form)\["(.*)"\]
and then take the second match.

What's the most efficient way to change the last element in a '/' delimited string

I have a string object in c# with a bunch of elements delimited by '/' characters. The string will look something like this:
"element1/element2/element3/element4"
What's the most efficient way to change the last element in the '/' delimited string?
Use string.LastIndexOf:
string s = "element1/element2/element3/element4";
s = s.Substring(0, s.LastIndexOf('/') + 1) + "foo";
If this is a filename/path string, you should use the System.IO.Path for this.
is there a 'lastIndexOf' in the C# String class? ( I don't code in C# normally ), if it exists you could use that to get a reference to the last / in the string, and that / precedes the last element of your string.
Like Joel suggests.. maybe something like this:
string path = (System.IO.Path.GetDirectoryName(#"element1/element2/element3/element4") +
System.IO.Path.DirectorySeparatorChar + "foo");
string new_path = path.Replace(System.IO.Path.DirectorySeparatorChar, '/');

Categories

Resources