简体   繁体   中英

Match a single occurrence of a string in a sentence using regEx

If a sentence says

"Hello Hello"

the test should return false, but if its something like

"Hello Jhon"

it returns true.

I thought this is all i had to do /(hello){1}/

A simple solution that doesn't complicate the regex, but counts the number of matches in a given string:

function isValid(str) {
   return (str.match(/hello/gi) || []).length === 1;
}

This RegEx will match any repeated word:

(\b\w+\b).+\1

Explanation:

From Regexper.com 正则表达式

Code

To check that a string doesn't contain a match:

!("testing testing 1 2 3...".match(/(\b\w+\b).+\1/)) #=> false
!("testing 1 2 3...".match(/(\b\w+\b).+\1/)) #=> true

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