首页 > 解决方案 > regex for a word but avoiding it if they are making another word

问题描述

Data:

Japan is beautiful country. AU is the telecom company of japan, au networks are very good. Japan is famous for good restaurants.


I need a RegEx to find the 'au' or 'AU' only even if have spaces before and after, but if it is within a word like 'beautiful' and 'restaurants' I want to avoid it.

Attempts

"/(?:au)/"

"/\P{au}/u"

"/(?:\A|\s)au(?:\s|\Z)/"

"/[^a-zA-Z]/"

if($word == 'au') {

}

标签: phpregex

解决方案


You can try this and just remove global handler if you want to search one time.

/(( )|^)(au)(( )|$)/gmi

I'm not sure what language you're using. I would match it using Perl with below method.

my $string = "Japan is beautiful country. AU is the telecom company of japan, au networks are very good. Japan is famous for good restaurants.";
my $matched; 
if($string=~m/(( )|^)(au)(( )|$)/gmi) {
   $matched = $2; ## This is AU, au Au or aU
}
## do something with $matched here

Sample of the match below.

enter image description here


推荐阅读