正则表达式只匹配整个单词

时间:2009-11-17 19:49:18

标签: regex word-boundary

我有一个正则表达式,我用它来查找给定内容块中的所有单词,不区分大小写,包含在存储在数据库中的词汇表中。这是我的模式:

/($word)/i

问题是,如果我使用/(Foo)/i,则Food之类的字词会匹配。在单词的两边都需要有空格或单词边界。

如果在句子的开头,中间或结尾处有单词,我如何修改我的表达式以仅匹配单词Foo

7 个答案:

答案 0 :(得分:96)

使用字边界:

/\b($word)\b/i

或者如果您正在搜索“S.P.E.C.T.R.E”。比如在SinanÜnür的例子中:

/(?:\W|^)(\Q$word\E)(?:\W|$)/i

答案 1 :(得分:36)

要匹配任何整个单词,您将使用模式(\w+)

假设您正在使用PCRE或类似的东西:

enter image description here

从此实例中截取的屏幕截图:http://regex101.com/r/cU5lC2

使用(\w+)

匹配命令行上的任何整个单词

我将使用phpsh interactive shell上的Ubuntu 12.10通过称为PCRE regex engine的方法展示preg_match

启动phpsh,将一些内容放入变量中,匹配单词。

el@apollo:~/foo$ phpsh

php> $content1 = 'badger'
php> $content2 = '1234'
php> $content3 = '$%^&'

php> echo preg_match('(\w+)', $content1);
1

php> echo preg_match('(\w+)', $content2);
1

php> echo preg_match('(\w+)', $content3);
0

preg_match方法使用PHP语言中的PCRE引擎来分析变量:$content1$content2$content3以及(\w)+模式。

$ content1和$ content2至少包含一个单词,$ content3不包含。

将命令行上的多个文字与(dart|fart)

匹配
el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'farty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(dart|fart)', $gun1);
1

php> echo preg_match('(dart|fart)', $gun2);
1

php> echo preg_match('(dart|fart)', $gun3);
1

php> echo preg_match('(dart|fart)', $gun4);
0

变量gun1和gun2包含字符串dart或fart。 gun4没有。但是,查找单词fart匹配farty可能会出现问题。要解决此问题,请在正则表达式中强制执行单词边界。

将命令行上的文字与词边界匹配。

el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'farty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(\bdart\b|\bfart\b)', $gun1);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun2);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun3);
0

php> echo preg_match('(\bdart\b|\bfart\b)', $gun4);
0

所以它与前一个示例相同,只是内容中不存在带有fart字边界的\b字:farty

答案 2 :(得分:8)

使用\b会产生令人惊讶的结果。你最好弄清楚一个单词与其定义之间的区别,并将这些信息合并到你的模式中。

#!/usr/bin/perl

use strict; use warnings;

use re 'debug';

my $str = 'S.P.E.C.T.R.E. (Special Executive for Counter-intelligence,
Terrorism, Revenge and Extortion) is a fictional global terrorist
organisation';

my $word = 'S.P.E.C.T.R.E.';

if ( $str =~ /\b(\Q$word\E)\b/ ) {
    print $1, "\n";
}

输出:

Compiling REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b"
Final program:
   1: BOUND (2)
   2: OPEN1 (4)
   4:   EXACT  (9)
   9: CLOSE1 (11)
  11: BOUND (12)
  12: END (0)
anchored "S.P.E.C.T.R.E." at 0 (checking anchored) stclass BOUND minlen 14
Guessing start of match in sv for REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b" against "S.P
.E.C.T.R.E. (Special Executive for Counter-intelligence,"...
Found anchored substr "S.P.E.C.T.R.E." at offset 0...
start_shift: 0 check_at: 0 s: 0 endpos: 1
Does not contradict STCLASS...
Guessed: match at offset 0
Matching REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b" against "S.P.E.C.T.R.E. (Special Exec
utive for Counter-intelligence,"...
   0           |  1:BOUND(2)
   0           |  2:OPEN1(4)
   0           |  4:EXACT (9)
  14      |  9:CLOSE1(11)
  14      | 11:BOUND(12)
                                  failed...
Match failed
Freeing REx: "\b(S\.P\.E\.C\.T\.R\.E\.)\b"

答案 3 :(得分:1)

使用字边界\ b,

以下(使用四个转义)适用于我的环境:Mac,safari版本10.0.3(12602.4.8)

var myReg = new RegExp(‘\\\\b’+ variable + ‘\\\\b’, ‘g’)

答案 4 :(得分:1)

对于那些想要在其代码中验证枚举的人,您可以按照指南进行操作

在Regex World中,您可以使用^来开始一个字符串,并使用$来结束它。您可以将它们与|结合使用:

^(Male)$|^(Female)$

仅在MaleFemale情况下返回true。

答案 5 :(得分:0)

如果您在记事本++中完成

docker run

将为您提供整个单词,您可以添加括号以将其作为一个整体。示例:[\w]+ 。我想将conv1 = Conv2D(64, (3, 3), activation=LeakyReLU(alpha=a), padding='valid', kernel_initializer='he_normal')(inputs)移到其自己的行中作为注释,并替换当前的激活。在记事本++中,可以使用以下查找命令完成此操作:

LeakyReLU

替换命令变为:

([\w]+)( = .+)(LeakyReLU.alpha=a.)(.+)

空格是为了在我的代码中保留正确的格式。 :)

答案 6 :(得分:-1)

获取字符串中的所有“单词”

library(ggplot2) library(dplyr) library(forcats) df <- data.frame(cat = c(rep("A",9),rep("B",11)), grp = c(rep("C",3),rep("D",3),rep("F",3), rep("C",3),rep("D",3),rep("E",2),rep("F",3)), yrs = c(rep(c("2017","2018","2019"),5),"2017","2019","2017","2018","2019"), per = c(2.4,2.5,3.2, 15.3,17,16.7, 82.4,80.5,80.1, 8.6,9.6,15.2, 36.2,42.2,40.4, 1.7,1.1,53.4, 48.2,43.4)) df %>% ggplot(aes(x = "scale", y = per, fill = fct_reorder(grp, per))) + # geom_bar(stat="identity") + geom_col() + geom_text(aes(label= round(per,1)), position=position_stack(vjust=0.5), size= 3) + facet_grid(vars(yrs),vars(cat)) + coord_flip() + theme_bw() + xlab("") + ylab("") + ggtitle("How to sort ") + theme(legend.position="bottom", legend.title = element_blank(), plot.title = element_text(hjust = 0.5), axis.text = element_blank(), axis.ticks = element_blank())

基本上/([^\s]+)/g表示空格(或匹配非空格组)
别忘了^/s代表贪婪