c sharp regex替换任何单词的第一个或最后一个字符(c sharp regex replace first or last character of any word)
IT问题网 2021-01-22 00:00:00
问 题
想要使用正则表达式删除任何单词的第一个和最后一个字符....
例如..
(hello)(world)将返回=== hello world
和(he / llo)(wo / rld)将返回== ==== he / llo wo / rld
或// hello world /将返回========= hello world
或(hello)(w / orld)stackoverflow)将返回=== hello w / orld stackoverflow
(何(lo)wo(r)ld将返回=====他(lo wo(r)ld
>
我不想替换所有括号..我希望替换任何单词的第一个和最后一个括号.....
我试试这个...
temp = regex.replace(temp,@"^ [!@#$%^*()_ + = [{]};: lt;gt; | ./ , \''"" - ] +","");
但这个正则表达式只能删除first character if found ....
解决方案
%^*()_ + = [{]};:lt;gt; | ./?,\''" " - ] +"," ");
但这个正则表达式只能删除first character if found ....
为什么要使用正则表达式?
// 我个人认为这是一种扩展方法
public static string replaceoccurrence( this string str, string target, string replacement, int count)
{
int pos = -1;
int 计算= 0 ;
string result = " ";
执行
{
pos =(pos gt; = 0 )? str.indexof(target,pos + 1):pos = str.indexof(target);
if (pos gt; = 0 )
{
count ++;
}
} while (pos gt; = 0 amp;amp;!; count!= count);
if (pos gt; = 0 )
{
result = str.insert(pos,replacement).remove(pos + replacement.length,target.length);
}
返回结果;
}
用法:
string x = " (hello)(world)";
string y = " ";
y = replaceoccurrence(x," ("," ^", 1 ); // result ="^ hello)(world)"
y = replaceoccurrence(x," ("," ^", 2 ); // result ="(hello)^ world)"
y = replaceoccurrence(x," )" ," ^", 2 跨度>); // result ="(hello)(world ^"
y = replaceoccurrence(x," ("," zzzz", 2 ); // result ="(hello)zzzzworld)"
y = replaceoccurrence(x," )"," ", 2 跨度>); // result ="(hello)(world"
分享: