简体   繁体   English

仅在单词唯一时匹配

[英]matching a word only if it is unique

I've spent the day trying to use regex to match a word only where the word is unique. 我花了整整一天的时间尝试使用正则表达式仅在单词唯一的情况下匹配单词。 It's not working and I can't figure out what I'm doing wrong. 它不起作用,我无法弄清楚我在做什么错。

I need something that will match only a unique instance of "ST", such as: 我需要一些仅与“ ST”的唯一实例匹配的东西,例如:

  • "1 MARY ST WASHINGTON" “ 1 MARY ST华盛顿”

but fail with these: 但这些失败:

  • "1 ST MARY ST WASHINGTON" “ 1 ST MARY ST华盛顿”
  • "1 ST MARY ST MT ST HELENS" “ 1 ST MARY ST MT ST HELENS”
  • "1 MARY RD WE ST WASHINGTON" “1 MARY RD WE ST华盛顿”
  • "1 MARY RD WASHINGTON" “华盛顿1 MARY RD”

I thought this lookahead would work, but no such luck: 我以为可以提前进行,但运气不好:

(\bST\b)(?!(\bST\b))

What am I missing? 我想念什么?

You can use RegExp /\\bST\\b/g and .match() , check .length of matched string 您可以使用RegExp /\\bST\\b/g.match() ,检查匹配字符串的.length

 const matches = (str, re = /\\bST\\b/g, match = str.match(re)) => !!match && match.length === 1; const arr = [ "1 MARY ST WASHINGTON" , "1 ST MARY ST WASHINGTON" , "1 ST MARY ST MT ST HELENS" , "1 MARY RD WEST WASHINGTON" , "1 MARY RD WASHINGTON" ]; console.log(arr.map(s => matches(s))); 

You can use following pattern: 您可以使用以下模式:

^(?!(.*\bST\b){2,}).*\bST\b

This does a negative lookahead right away in which it checks if there are 2 or more occurrences of \\bST\\b . 这会立即进行否定的前瞻,它会检查\\bST\\b是否出现2次或更多次。 If there aren't, it moves on in the pattern and checks if there is at least one. 如果没有,它将按模式继续并检查是否至少有一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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