正则表达式:匹配除指定单词之外的单词

时间:2015-01-22 12:17:32

标签: regex

如何使用正则表达式匹配任何单词而不显示指定单词

我想要消除这个词"你"

我有一些例子:

you eat
you handsome
you die
you will
you lie
and others

所以,这个程序结果:

eat
handsome
die
will
lie

6 个答案:

答案 0 :(得分:3)

PCRE方法

如果您使用 PCRE (perl兼容正则表达式),您可以使用跳过/失败标记,如下所示:

you(*SKIP)(*FAIL)|\b(\w+)\b

<强> Working demo

enter image description here

然后,您是否可以访问捕获组:

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`

引用 regular-expressions.info

的段落
  

PCRE是Perl兼容正则表达式的缩写。这是名字   由Phillip Hazel用C语言编写的开源库。图书馆   兼容大量的C编译器和操作   系统。许多人从PCRE派生出库来制作它   与其他编程语言兼容。正则表达式的功能   包括PHP,Delphi和R,以及Xojo(REALbasic)都是基于   在PCRE上。该库也包含在许多Linux发行版中   共享的.so库和.h头文件。

丢弃技术方法

另外,如果您没有使用 pcre 正则表达式,那么您可以使用通常名为 discard technique 。它包括使用 OR 链匹配所有您不想要的模式,并在链的末尾使用您感兴趣的模式并捕获它:

discard patt1 | discard patt2 | discard pattN |(grab this!)

对于您的情况,您可以使用:

you|\b(\w+)\b
 ^       ^--- Capture this    
 +-- Discard 'you'

答案 1 :(得分:1)

使用字边界和否定前瞻:

\b(?!you\b)\w+\b

答案 2 :(得分:1)

试试这个:

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++;
}

但你不需要Regex。

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", "");
}

答案 3 :(得分:1)

如果你想使用正则表达式,那么如果用匹配器组$ 2替换它,它将起作用:

/(you (\w+))|(\w+ \w+)/g

http://regexr.com/3a8uk

答案 4 :(得分:0)

这个问题怎么样?

are you serious ?
are you ?
you are greatfull

和结果:

are serious ?
are ?
are greatefull

答案 5 :(得分:-1)

/you (.*)/

匹配组将是除了你之外的所有内容。