I need to Match the second and subsequent occurances of the * character using a regular expression. I'm actually using the Replace method to remove them so here's some examples of before and after:
我需要使用正则表达式匹配*字符的第二次和随后的出现。我实际上是用替换法来移除它们这里有一些前后的例子:
test* -> test* (no change)
*test* -> *test
test** *e -> test* e
Is it possible to do this with a regular expression? Thanks
有可能用正则表达式来实现这一点吗?谢谢
3 个解决方案
#1
4
If .NET can cope with an arbitrary amount of look behind, try replacing the following pattern with an empty string:
如果.NET可以处理任意数量的查找,尝试用一个空字符串替换下面的模式:
(?<=\*.*)\*
.
。
PS Home:\> 'test*','*test*','test** *e' -replace '(?<=\*.*)\*',''
test*
*test
test* e
Another way would be this pattern:
另一种方式是这种模式:
(?<=\*.{0,100})\*
where the number 100
can be replaced with the size of the target string.
可以用目标字符串的大小替换数字100。
And testing the following with Mono 2.0:
并使用Mono 2.0测试如下:
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
Regex r = new Regex(@"(?<=\*.*)\*");
Console.WriteLine("{0}", r.Replace("test*", ""));
Console.WriteLine("{0}", r.Replace("*test*", ""));
Console.WriteLine("{0}", r.Replace("test** *e", ""));
}
}
also produced:
还生产:
test*
*test
test* e
#2
0
Non optimal, but another approach. Record the index of the first occurrence, replace all occurrence, and reinsert the first occurrence at the recored index.
不是最优的,而是另一种方法。记录第一次出现的索引,替换所有的发生,并重新插入记录索引中的第一个事件。
#3
0
$str =~ s/\*/MYSPECIAL/; #only replace the first *
$str =~ s/\*//g; #replace all *
$str =~ s/MYSPECIAL/\*/; #put * back
#1
4
If .NET can cope with an arbitrary amount of look behind, try replacing the following pattern with an empty string:
如果.NET可以处理任意数量的查找,尝试用一个空字符串替换下面的模式:
(?<=\*.*)\*
.
。
PS Home:\> 'test*','*test*','test** *e' -replace '(?<=\*.*)\*',''
test*
*test
test* e
Another way would be this pattern:
另一种方式是这种模式:
(?<=\*.{0,100})\*
where the number 100
can be replaced with the size of the target string.
可以用目标字符串的大小替换数字100。
And testing the following with Mono 2.0:
并使用Mono 2.0测试如下:
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
Regex r = new Regex(@"(?<=\*.*)\*");
Console.WriteLine("{0}", r.Replace("test*", ""));
Console.WriteLine("{0}", r.Replace("*test*", ""));
Console.WriteLine("{0}", r.Replace("test** *e", ""));
}
}
also produced:
还生产:
test*
*test
test* e
#2
0
Non optimal, but another approach. Record the index of the first occurrence, replace all occurrence, and reinsert the first occurrence at the recored index.
不是最优的,而是另一种方法。记录第一次出现的索引,替换所有的发生,并重新插入记录索引中的第一个事件。
#3
0
$str =~ s/\*/MYSPECIAL/; #only replace the first *
$str =~ s/\*//g; #replace all *
$str =~ s/MYSPECIAL/\*/; #put * back