Find substring between slashes and replace that part in ASP.NET C# - c#

Using ASP.NET C#, I need to find and replace the word string1 between the last two slashes and replace with string2
Example:
string fullStr = "/this/is/string1/part";
string subStr = "function";
string finalStr = "/this/is/" + subStr + "/part";

And a regex solution:
string fullStr = "this/is/string1/part";
string subStr = "function";
var newstr = Regex.Replace(fullStr, #"/[^/]+/(?=[^/]+$)", m => "/" + subStr + "/");

I don't feel a need of regex here.
string fullStr = "/this/is/string1/part";
string subStr = "function";
string[] fullStrParts = fullStr.Split('/');
fullStrParts[fullStrParts.Length - 2] = subStr;
string finalStr = string.Join("/", fullStrParts);

Related

C# - Get All Words Between Chars

I have string:
string mystring = "hello(hi,mo,wo,ka)";
And i need to get all arguments in brackets.
Like:
hi*mo*wo*ka
I tried that:
string res = "";
string mystring = "hello(hi,mo,wo,ka)";
mystring.Replace("hello", "");
string[] tokens = mystring.Split(',');
string[] tokenz = mystring.Split(')');
foreach (string s in tokens)
{
res += "*" + " " + s +" ";
}
foreach (string z in tokenz)
{
res += "*" + " " + z + " ";
}
return res;
But that returns all words before ",".
(I need to return between
"(" and ","
"," and ","
"," and ")"
)
You can try to use \\(([^)]+)\\) regex get the word contain in brackets,then use Replace function to let , to *
string res = "hello(hi,mo,wo,ka)";
var regex = Regex.Match(res, "\\(([^)]+)\\)");
var result = regex.Groups[1].Value.Replace(',','*');
c# online
Result
hi*mo*wo*ka
This way :
Regex rgx = new Regex(#"\((.*)\)");
var result = rgx.Match("hello(hi,mo,wo,ka)");
Split method has an override that lets you define multiple delimiter chars:
string mystring = "hello(hi,mo,wo,ka)";
var tokens = mystring.Replace("hello", "").Split(new[] { "(",",",")" }, StringSplitOptions.RemoveEmptyEntries);

Adding chars before and after each word in a string

Imagine we have a string as :
String mystring = "A,B,C,D";
I would like to add an apostrophe before and after each word in my string.Such as:
"'A','B','C','D'"
How can i achieve that?
What's your definition of a word? Anything between commas?
First get the words:
var words = mystring.Split(',');
Then add the apostrophes:
words = words.Select(w => String.Format("'{0}'", w));
And turn them back into one string:
var mynewstring = String.Join(",", words);
mystring = "'" + mystring.replace(",", "','") + "'";
I would let each "word" be determined by the regex \b word boundary. So, you have:
var output = Regex.Replace("A,B,C,D", #"(\b)", #"'$1");
string str = "a,b,c,d";
string.Format("'{0}'", str.Replace(",", "','"));
or
string str = "a,b,c,d";
StringBuilder sb = new StringBuilder(str.Length * 2 + 2);
foreach (var c in str.ToCharArray())
{
sb.AppendFormat((c == ',' ? "{0}" : "'{0}'"), c);
}
str = sb.ToString();
string mystring = "A,B,C,D";
string[] array = mystring.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string newstring = "";
foreach (var item in array)
{
newstring += "'" + item + "',";
}
newstring = newstring.Remove(newstring.Length - 1);
Console.WriteLine(newstring);
Output will be;
'A','B','C','D'
Here a DEMO.
Or more simple;
string mystring = "A,B,C,D";
Console.WriteLine(string.Format("'{0}'", mystring.Replace(",", "','")));
you can use regular expressions to solve this problem
like this:
string words= "A,B,C,D";Regex reg = new Regex(#"(\w+)");words = reg.Replace(words, match=> { return string.Format("'{0}'", match.Groups[1].Value); });

Want to assign HTML value to String variable

I want to assign HTML snippet to string variable.
something like -
string div = "<table><tr><td>Hello</td></tr></table>"; // It should return only 'Hello'
Please suggest.
string div = "<table><tr><td>Hello</td></tr></table>"; // It should return only 'Hello
var doc = new XmlDocument();
doc.LoadXml(div);
string text = doc.InnerText;
Do you also need the Jquery version of this?
If you are sure that the HTML won't change between the string you want to get, you can simply do a Substring between the two constants string and you will get your string into your variable.
const string prefix = "<table>";
const string suffix = "</table>";
string s = prefix + "TEST" + suffix ;
string s2 = s.Substring(prefix.Length, s.IndexOf(suffix, StringComparison.Ordinal) - prefix.Length);
Here is the Regex version:
const string prefix = "<table>";
const string suffix = "</table>";
string s = prefix + "TEST" + suffix;
string s2 = Regex.Match(s, prefix + "(.*)" + suffix).Groups[1].Value;

Replace with pattern matching

How can I use the String.Replace function to use Patterns?
What I would like to do:
newTextBox = newTextBox.Replace("<Value> #'a string of any number of chars#' </Value>",
"<Value>" + textBoxName + "</Value>");
#'a string of any number of chars#' can be any string.
Use a regular expression:
newTextBox.Text =
Regex.Replace(
newTextBox.Text,
#"<Value>[^\<]+</Value>",
"<Value>" + textBoxName.Text + "</Value>");
Could also do it like this?:
const string textBoxName = "textBoxName";
var newTextBox = "<Value>{0}</Value>".Replace("{0}", textBoxName);
You should be using Regex that's why it exists. Regex
With Regex reference:
using System.Text.RegularExpressions;
And the characters you want to replace: [0-9a-zA-Z_#' ]
newTextBox.Text = Regex.Replace(
"<Value> #'a string of any number of chars#' </Value>",
#"<Value>[0-9a-zA-Z_#' ]*</Value>",
"<Value>" + textBoxName.Text + "</Value>",
RegexOptions.IgnoreCase);

How can I split a string to obtain a filename?

I am trying to split the string. Here is the string.
string fileName = "description/ask_question_file_10.htm"
I have to remove "description/" and ".htm" from this string. So the result I am looking for "ask_question_file_10". I have to look for "/" and ".htm" I appreciate any help.
You can use the Path.GetFileNameWithoutExtension Method:
string fileName = "description/ask_question_file_10.htm";
string result = Path.GetFileNameWithoutExtension(fileName);
// result == "ask_question_file_10"
string fileName = Path.GetFileNameWithoutExtension("description/ask_question_file_10.htm")
try
string myResult = fileName.SubString (fileName.IndexOf ("/") + 1);
if ( myResult.EndsWith (".htm" ) )
myResult = myResult.SubString (0, myResult.Length - 4);
IF it is really a path then you can use
string myResult = Path.GetFileNameWithoutExtension(fileName);
EDIT - relevant links:
http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension.aspx
http://msdn.microsoft.com/en-us/library/hxthx5h6.aspx
http://msdn.microsoft.com/en-us/library/2333wewz.aspx
http://msdn.microsoft.com/en-us/library/system.string.length.aspx
string fileName = "description/ask_question_file_10.htm";
string name = Path.GetFileNameWithoutExtension(fileName);

Categories