how to delete specify string in C# - c#

When i program,i want to delete a specify string in a long string.
For example:
The source string is:
abcdffff<fdfs>adbcccc
abcdffff<fdferfefs>adbcccc
abcdffff<fdffefes>adbcccc
abcdffff<fdffefefs>adbcccc
The i want to delete the string like <fdfs>
The result should be:
abcdffffadbcccc
abcdffffadbcccc
abcdffffadbcccc
abcdffffadbcccc
How could i do?
This is my code:
public string formatMailMessageBody(string herf,string notifyinfo)
{
StringBuilder sb = new StringBuilder();
sb.Append(notifyinfo.Replace("〈%〉", "") + "<br><br>");
sb.Append("单击下面的链接查看您当前任务:<br>");
sb.Append("<a href='" + herf + "'><b>" + herf + "</b></a>");
string s = sb.ToString();
return sb.ToString();
}
Is it right?

Note that the following code is applicable only if the string you want to delete has this format <...> (no other pairs of <> inside):
var output = Regex.Replace(input, #"\<[^>]*\>", "");
The Regex class is located in the namespace System.Text.RegularExpressions.

Related

Extract values from html tags in a string?

I have the following strings of HTML tags:
string markup = "<b>this</b><s/><i>is</i><s/><r>text</r>";
string markup2 = "<b>this</b><i>hello</i><i>is</i><r>text</r>";
string markup3 = "<s/><b>this</b><i>hello</i><i>is</i><r>text</r>";
string markup4 = "<b>this</b><i>hello</i><i>is</i><r>text</r><s/>";
string markup5 = "<s/><b>this</b><i>hello</i><i>is</i><r>text</r><s/>";
string markup6 = "<s/><b>this</b><i>hello</i><s/><s/><s/><r>text</r><i>is</i><s/>";
How can I extract the value inside each tag regardless of which string is used, and printing a space instead of the s tag
If the tags are "empty" (only "< s />") you basically replace a string in a string.
e.g.:
string x = markup.Replace("<s/>", " "); //Replaces all occurrences of <s/>
Try this:
var input = "<b>this</b><s/><i>is</i><s/><r>text</r>";
var tmp = input.Replace("<s/>", " "); // <s/> Replace
var final = Regex.Replace(tmp, "<.*?>", string.Empty); // HTML delete

Remove brackets dots and white spaces from string

I am using asp.net mvc c#.This is my string
string filename = "excluder version(1). final"
I want to concatinate string with result
filename = "excluderversion1final"
How to do this? I dont want to use the javascript or jquery. Need to do it code behind
Sounds like a good candidate for Regex.Replace:
private static readonly Regex RemovalRegex = new Regex(#"\s|[().]");
...
public static string RemoveUnwantedCharacters(string input)
{
return RemovalRegex.Replace(input, "");
}
Note that this will handle all whitespace, not just the space character, and you can easily amend the regular expression to add extra bits.
If you just need to remove these three characters (since we're talking about small strings like file names), you can use regular string.Replace:
filename.Replace("{", "")
.Replace("}", "")
.Replace("(", "")
.Replace(")", "")
.Replace(".", "")
.Replace(" ", "");
Or maybe, simplifying it:
string fileName = "excluder version(1). final";
new List<string> { "{", "}", "(", ")", ".", " " }
.ForEach(character => fileName = fileName.Replace(character, ""));
You can use String.Replace Method:-
filename = filename.Replace(" ","").Replace("(","").Replace(")","").Replace(".","");
You can wrap this inside an extension method like this:-
public static class StringExtention
{
public static string RemoveUnwantedCharacters(this string s)
{
StringBuilder sb = new StringBuilder(s);
sb.Replace("(", "");
sb.Replace(")", "");
sb.Replace(" ", "");
sb.Replace(".", "");
return sb.ToString();
}
}
You can use this as: filename = filename.RemoveUnwantedCharacters();
But, since there is a possiblity of whitespaces too and not just space, I guess Regex is the best answer here as answered by #JonSkeet :)
By using regex:
string header = "excluder version(1). final";
Regex rgx = new Regex(#"\W+|\s");
string result = rgx.Replace(header, "");

Replacement in a String with a regular expression

I'm trying to replace a string in C# with the class Regex but I don't know use the class properly.
I want replace the next appearance chain in the String "a"
":(one space)(one or more characters)(one space)"
by the next regular expression
":(two spaces)(one or more characters)(three spaces)"
Will anyone help me and give me the code and explains me the regular expresion used?
you can use string.Replace(string, string)
try this one.
http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
try this one
private String StrReplace(String Str)
{
String Output = string.Empty;
String re1 = "(:)( )((?:[a-z][a-z]+))( )";
Regex r = new Regex(re1, RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match m = r.Match(Str);
if (m.Success)
{
String c1 = m.Groups[1].ToString();
String ws1 = m.Groups[2].ToString() + " ";
String word1 = m.Groups[3].ToString();
String ws2 = m.Groups[4].ToString() + " ";
Output = c1.ToString() + ws1.ToString() + word1.ToString() + ws2.ToString() + "\n";
Output = Regex.Replace(Str, re1, Output);
}
return Output;
}
Using String.Replace
var str = "Test string with : .*. to replace";
var newstr = str.Replace(": .*. ", ": .*. ");
Using Regex.Replace
var newstr = Regex.Replace(str,": .*. ", ": .*. ");

error : The given path's format is not supported

Getting this error The given path's format is not supported. at this line
System.IO.Directory.CreateDirectory(visit_Path);
Where I am doing mistake in below code
void Create_VisitDateFolder()
{
this.pid = Convert.ToInt32(db.GetPatientID(cmbPatientName.SelectedItem.ToString()));
String strpath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
String path = strpath + "\\Patients\\Patient_" + pid + "\\";
string visitdate = db.GetPatient_visitDate(pid);
this.visitNo = db.GetPatientID_visitNo(pid);
string visit_Path = path +"visit_" + visitNo + "_" + visitdate+"\\";
bool IsVisitExist = System.IO.Directory.Exists(path);
bool IsVisitPath=System.IO.Directory.Exists(visit_Path);
if (!IsVisitExist)
{
System.IO.Directory.CreateDirectory(path);
}
if (!IsVisitPath)
{
System.IO.Directory.CreateDirectory(visit_Path);\\error here
}
}
getting this value for visit_Path
C:\Users\Monika\Documents\Visual Studio 2010\Projects\SonoRepo\SonoRepo\bin\Debug\Patients\Patient_16\visit_4_16-10-2013 00:00:00\
You can not have : in directory name, I suggest you to use this to string to get date in directory name:
DateTime.Now.ToString("yyyy-MM-dd hh_mm_ss");
it will create timestamp like:
2013-10-17 05_41_05
additional note:
use Path.Combine to make full path, like:
var path = Path.Combine(strpath , "Patients", "Patient_" + pid);
and last
string suffix = "visit_"+visitNo+"_" + visitdate;
var visit_Path = Path.Combine(path, suffix);
In general always use Path.Combine to create paths:
String strPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
String path = Path.Combine(strPath,"Patients","Patient_" + pid);
string visitdate = db.GetPatient_visitDate(pid);
this.visitNo = db.GetPatientID_visitNo(pid);
string fileName = string.Format("visit_{0}_{1}", visitNo, visitdate);
string visit_Path = Path.Combine(path, fileName);
bool IsVisitExist = System.IO.Directory.Exists(path);
bool IsVisitPath=System.IO.Directory.Exists(visit_Path);
To replace invalid characters from a filename you could use this loop:
string invalidChars = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
foreach (char c in invalidChars)
{
visit_Path = visit_Path.Replace(c.ToString(), ""); // or with "."
}
You can't have colons : in file paths
You can't use colons (:) in a path. You can for example Replace() them with dots (.).
Just wanted to add my two cents.
I assigned the path from a text box to string and also adding additional strings, but I forgot to add the .Text to the text box variable.
So instead of
strFinalPath = TextBox1.Text + strIntermediatePath + strFilename
I wrote
strFinalPath = TextBox1 + strIntermediatePath + strFilename
So the path became invalid because it contained invalid characters.
I was surprised that c# instead of rejecting the assignment because of type mismatch, assigned invalid value to the final string.
So look at the path assignment string closely.

String: replace last ".something" in a string?

I have some string and I would like to replace the last .something with a new string. As example:
string replace = ".new";
blabla.test.bla.text.jpeg => blabla.test.bla.text.new
testfile_this.00001...csv => testfile_this.00001...new
So it doesn't matter how many ..... there are, I'd like to change only the last one and the string what after the last . is coming.
I saw in C# there is Path.ChangeExtension but its only working in a combination with a File - Is there no way to use this with a string only? Do I really need regex?
string replace = ".new";
string p = "blabla.test.bla.text.jpeg";
Console.WriteLine(Path.GetFileNameWithoutExtension(p) + replace);
Output:
blabla.test.bla.text.new
ChangeExtension should work as advertised;
string replace = ".new";
string file = "testfile_this.00001...csv";
file = Path.ChangeExtension(file, replace);
>> testfile_this.00001...new
You can use string.LastIndexOf('.');
string replace = ".new";
string test = "blabla.test.bla.text.jpeg";
int pos = test.LastIndexOf('.');
if(pos >= 0)
string newString = test.Substring(0, pos-1) + replace;
of course some checking is required to be sure that LastIndexOf finds the final point.
However, seeing the other answers, let me say that, while Path.ChangeExtension works, it doesn't feel right to me to use a method from a operating system dependent file handling class to manipulate a string. (Of course, if this string is really a filename, then my objection is invalid)
string s = "blabla.test.bla.text.jpeg";
s = s.Substring(0, s.LastIndexOf(".")) + replace;
No you don't need regular expressions for this. Just .LastIndexOf and .Substring will suffice.
string replace = ".new";
string input = "blabla.bla.test.jpg";
string output = input.Substring(0, input.LastIndexOf('.')) + replace;
// output = "blabla.bla.test.new"
Please use this function.
public string ReplaceStirng(string originalSting, string replacedString)
{
try
{
List<string> subString = originalSting.Split('.').ToList();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < subString.Count - 1; i++)
{
stringBuilder.Append(subString[i]);
}
stringBuilder.Append(replacedString);
return stringBuilder.ToString();
}
catch (Exception ex)
{
if (log.IsErrorEnabled)
log.Error("[" + System.DateTime.Now.ToString() + "] " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + " :: " + System.Reflection.MethodBase.GetCurrentMethod().Name + " :: ", ex);
throw;
}
}

Categories

Resources