Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#字符串替换问题_C#_String - Fatal编程技术网

C#字符串替换问题

C#字符串替换问题,c#,string,C#,String,快速提问。我有一个从目录列表填充的列表框。每个文件都包含其名称和~######。我试图把它全部读入一个字符串,并用零替换~######。######可以是长度为1-6的数字,也可以是长度为0-9的任何数字。以下是我使用的代码: string listItem = (listBox1.SelectedItem.ToString().Replace("~*","")); 例如: Here223~123 ---> Here Here224~2321 ----> Here 我无法替换

快速提问。我有一个从目录列表填充的列表框。每个文件都包含其名称和~######。我试图把它全部读入一个字符串,并用零替换~######。######可以是长度为1-6的数字,也可以是长度为0-9的任何数字。以下是我使用的代码:

string listItem = (listBox1.SelectedItem.ToString().Replace("~*",""));
例如:

Here223~123  --->  Here
Here224~2321 ----> Here
我无法替换任何号码,因为在~

尝试之前我需要这些号码

listItem.Split("~")[0]
这将为您提供字符串数组中的第一个字符串,这样您就丢失了tilda和后面的字符串。

string listItem=Regex.Replace(listBox1.SelectedItem.ToString(),“~[0-9]{1,6}”,string.Empty)

string listItem = Regex.Replace(listBox1.SelectedItem.ToString(), "~[0-9]{1,6}", string.Empty);
应该这样做(不记得是否必须逃跑!)

那么:

string listItem = 
      listBox1.SelectedItem.ToString().Substring(0, 
           listBox1.SelectedItem.ToString().IndexOf("~"));

使用子字符串(int startIndex,int lenght)方法可能会更好:

string listItem = listBox1.SelectedItem.toString();
listItem = listitem.SubString(0, listItem.IndexOf("~"));

关键是string.replace不支持正则表达式


所以要么在“~”上拆分,要么使用正则表达式

我很想使用正则表达式,但我无法编译它。它认为有一个换行符是从“这很奇怪,正则表达式通常很好地处理换行符('\n's)。对于这样的问题,正则表达式也是一个很好的工具,特别是当它们变得更复杂时,因为拆分不是很具体。@Mike,只是缺少了一个
;试试看again@Rubens谢谢你的编辑,我还没注意到它把我的语法弄糟了!伙计,我主要是投票让你从9990跑到10k。但你今天似乎已经达到了极限。:-)@托马拉克,我今天已经得了232分;当你需要一个答案时,很难得到一个被接受的答案=)