Maison  >  Article  >  développement back-end  >  英文文章中过滤单词

英文文章中过滤单词

WBOY
WBOYoriginal
2016-08-26 10:28:231895parcourir

这是一段英文字符串

<code>When I was young,my uncle king of the jungle,one day he call me,and say we walk to the river,i asked why?
my uncle say, you must learn how to cherish the water.</code>

我想写一个只要该单词就能可以的正则表达式
这是我写的。

<code>[^a-zA-Z]young[^a-zA-Z]</code>

可是找不到文章第一个单词
英文文章中过滤单词

在线正则表达式

回复内容:

这是一段英文字符串

<code>When I was young,my uncle king of the jungle,one day he call me,and say we walk to the river,i asked why?
my uncle say, you must learn how to cherish the water.</code>

我想写一个只要该单词就能可以的正则表达式
这是我写的。

<code>[^a-zA-Z]young[^a-zA-Z]</code>

可是找不到文章第一个单词
英文文章中过滤单词

在线正则表达式

[^a-zA-Z] 改成 [^a-zA-Z]? 就可以了啊

<code>(^|[^a-zA-Z])you([^a-zA-Z]|$)
</code>

英文文章中过滤单词

(^|[^a-zA-Z])When([^a-zA-Z]|$) 我觉得这样就可以了,考虑了第一个单词和最后一个单词的情况,其实我觉得最简单的方式还是你在字符串的头部和尾部个加上一个空格或者其他一个特别的字符,这样你原来的正则就能成功匹配到了。

[^a-zA-Z]这个模式匹配一个 非“a到z或A到Z”的字符 ,When的前面并没有字符,自然匹配不到了。其他匹配到的单词也是匹配到了一个空格的。

如果你并不想空格,其实可以用转义字符b来匹配单词边界,这个转义字符可以匹配开头、结尾以及空格、标点形成的单词边界,本身并不会匹配到任何多余的字符。

\bWhen\b就可以了。

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn