简体   繁体   中英

how to get only fully matched string from match

I need to match "test" or "test," from a string like

"test, testhellowowo, wowtest,"

Attempt 1

test[,]?

it will match all three since all of the string include the test regardless what comes after.

Attempt 2

^test[,]?$

it won't match any unless the string is test or test,

Expected results

"test, testhellowowo, wowtest,".match(x) // should match `test,` 
"testhellowowo, wowtest,".match(x)  // should not match anything

You can use word boundaries

/\btest\b/g

They match at

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

If you need to include the punctuation mark you could also do /^test[,]?$/gm

^ matches beginning of string $ matches end of string

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