如何使用正则表达式匹配没有显示指定单词的任何单词
我想去掉“你”这个词
例如,我有一些单词:
you eat
you handsome
you die
you will
you lie
and others所以,这个程序的结果是:
eat
handsome
die
will
lie发布于 2015-01-22 20:35:21
PCRE方法
如果您使用 (兼容perl的正则表达式),您可以像这样利用的跳过/失败标志:
you(*SKIP)(*FAIL)|\b(\w+)\b

那么您是否可以访问您可以抓取的捕获群:
MATCH 1
1. [4-7] `eat`
MATCH 2
1. [12-20] `handsome`
MATCH 3
1. [25-28] `die`
MATCH 4
1. [33-37] `will`
MATCH 5
1. [42-45] `lie`
MATCH 6
1. [46-49] `and`
MATCH 7
1. [50-56] `others`引用的一段话
Perl是
兼容正则表达式的缩写。它是Phillip Hazel用C编写的开源库的名称。该库与大量的C编译器和操作系统兼容。许多人从PCRE派生库,以使其与其他编程语言兼容。Delphi和R以及Xojo (REALbasic)包含的正则表达式特性都是基于PCRE的。该库还包含在许多Linux发行版中,作为一个共享.so库和一个.h头文件。
丢弃技术方法
另一方面,如果您不使用pcre正则表达式,那么您可以使用一种优秀的正则表达式技术(在我看来是最好的),通常称为丢弃技术。它包括使用或链匹配您不想要的的所有模式,并在链的末尾使用您感兴趣的模式并捕获它:
discard patt1 | discard patt2 | discard pattN |(grab this!)对于您的情况,您可以使用:
you|\b(\w+)\b
^ ^--- Capture this
+-- Discard 'you'发布于 2015-01-22 20:24:14
使用单词边界和负向前视:
\b(?!you\b)\w+\b发布于 2015-01-22 20:25:30
试试这个:
String sourcestring = "source string to match with pattern";
Regex re = new Regex(@"^you (.*)/$",RegexOptions.Multiline |
RegexOptions.Singleline);
MatchCollection mc = re.Matches(sourcestring);
int mIdx=0;
foreach (Match m in mc)
{
for (int gIdx = 0; gIdx < m.Groups.Count; gIdx++)
{
Console.WriteLine("[{0}][{1}] = {2}", mIdx,
re.GetGroupNames()[gIdx],
m.Groups[gIdx].Value);
}
mIdx++;
}但你不需要正则表达式。
string[] words = new string[] { "you eat",
"you handsome",
"you die",
"you will",
"you lie",
"and others" };
foreach (var word in words)
{
var result = word.Replace("you", "");
}https://stackoverflow.com/questions/28088573
复制相似问题