简体   繁体   中英

Word not adjacent to word in regex?

i have some bad words set like :

'aaa','bbb','ccc'

( bad words can be also , "john","paul","ringo") ( sorry @cyilan)

i dont want to allow bad word immediately followed by another/same bad word

aaa can be followed by a non-bad word and then to be followed by a bad word :

  ...aaaRoyibbb...  //ok
  ...cccRoyiaaa...  //ok

   ...aaabbb...// NOT OK
   ...cccbbb...// NOT OK
   ...cccccc...// NOT OK

a bad word is not allowed to be immediately followed with another/same bad word

I've tried some regexps but with no success..

any help will be much appreciated

var str = "...aaabbb...";
if(!str.test(/(?:aaa|bbb|ccc){2}/)){
    // passed
}

Chat revealed that what OP really wanted was:

/^(?!(?:aaa|bbb|ccc)|.*(?:aaa|bbb|ccc){2}|.*(?:aaa|bbb|ccc)$)/

But really really:

^(?!(?:aaa|bbb|ccc)\b|.*\b(?:aaa|bbb|ccc)\s+(?:aaa|bbb|ccc)\b|.*\b(?:aaa|bbb|cc‌​c)$)
match = subject.match(/\b([a-z]{3})(?:(?!\1)|(?=\1))[a-z]+\b/i);
if (match != null) {
    // matched text: match[0]
    // match start: match.index
    // capturing group n: match[n]
} else {
    // Match attempt failed
}

The solution you're looking for is \\b. \\b is defined as a word break. If it follows white space or numbers, it matches if the following text is letters. If it follows letters, it matches if the following is not letters (ie not a continuous word). It can be effectively used as an anchor tag, like this:

\byourword\b

It would match:

This is yourword, but not mine.
yourword is found in this sentence.

But it would not match:

When yourwordis found in other words, this will not match.
And ifyourword is at the end of another word, it will still not match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM