删除符号“"从文本文件 [英] remove symbol "" from text file
本文介绍了删除符号“"从文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个文本< set><值><名称>"在文件中,现在我需要删除字符<"和>"在文本之间.我正在尝试以下代码
hi i have this text "<set> <value> <name>" in a file, now i need to remove the character "<" and ">" which is in between the text. im trying with the below code
private void button1_Click(object sender, EventArgs e)
{
sr = new StreamReader(sam);
textBox1.Text = sr.ReadLine();
string pattern = "\"(?=[<\"]+,)[>\"]+\"";
string result = Regex.Replace(textBox1.Text, pattern, m => m.Value.Replace("<", " "));
textBox2.Text = result;
sr.Close();
}
我对此正则表达式感到困惑,并且我得到了相同的输出
<设置><值><名称>"
请帮助....
im confused with this regular expression and im getting the same output
"<set> <value> <name>"
please help....
推荐答案
尝试以下代码:
Try the below code:
string pattern = "\"([^\"]+)\"";
value = Regex.Match(textToSearch, pattern).Value;
string[] removalCharacters = {"\""}; //or any other characters
foreach (string character in removalCharacters)
{
value = value.Replace(character, "");
}
我们只是删除了两个字符,我们知道它们是哪两个.在这种情况下,使用Regex似乎有点矫kill过正.如果要删除大量字符,那么我将进行扫描以创建要删除的字符的索引图,将字符串转换为数组,然后使用for循环跳过该图中的任何索引(最有可能HashSet< int>)以将字符插入到字符串生成器中,以避免O(n ^ 2)情况.但是,如果只是在这里去除字符,那么下面的代码就可以了.
We''re only removing two characters, and we know which two they are. Using Regex seems a bit like overkill in this case. If you were removing a large variation of characters, then I would do a scan to create an index-map of which characters to remove, convert the string into an array, and use a for loop the skips any index in that map (most likely a HashSet<int>) to insert the character''s into a string builder to avoid a O(n^2) situation. Yet, if this is only place where you''re stripping out characters, then the following code is just fine.
private void button1_Click(object sender, EventArgs e)
{
string s;
try
{
using (StreamReader sr = new StreamReader(sam))
{
s = sr.ReadLine();
}
}
catch
{
s = null;
}
textBox1.Text = s;
if(s != null)
{
s = s.Replace("<", string.Empty);
s = s.Replace(">", string.Empty);
}
textBox2.Text = s;
}
这篇关于删除符号“"从文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文