正则表达式匹配字符串但不匹配子字符串

时间:2020-02-23 01:24:55

标签: regex

我有这个正则表达式 async getLatLong(prediction){ //console.log(prediction); const key="MY_API_KEY"; const geoUrl=`https://maps.googleapis.com/maps/api/place/details/json?key=${key}&placeid=${prediction}`; try{ const georesult= await fetch(geoUrl); const gjson= await georesult.json(); this.setState({locations:gjson.result.geometry.location}); this.setState({ region:{ latitude:this.state.locations.lat, longitude:this.state.locations.lng, latitudeDelta: 0.0922, longitudeDelta: 0.0421 } }); b.onRegionChange(this.state.region); } catch(err){ console.error(err); } }和以下字符串

  1. /\$([^:\n]+)/
  2. gid$gid::
  3. $gid::
  4. ::$gid

目前running the regex on each string independently,我得到了这些匹配项

  1. bar$:$gid:f$oo
  2. gid
  3. gid
  4. [{gidgid]

我需要更改正则表达式,以便编号1中没有匹配项,而编号4中只有一个匹配项-中间的oo。换句话说,它仅匹配以$gid开头的字符串,该字符串从字符串的开头开始或紧接在冒号之后

提前谢谢!

2 个答案:

答案 0 :(得分:1)

您可能会发现其他示例,这些示例进一步限制了您的需求,但这似乎可以按照您的描述起作用:

(^|:)(\$[^:\n]+)

在这里https://regex101.com/r/HGtNw1/1

答案 1 :(得分:0)

我最终使用(php)

preg_match_all('/(^|:)\$(\w+)/m', $subject, $matches);

m选项和隐含的g选项(通过函数中的_all)是获得所需答案的关键。

https://www.phpliveregex.com/p/v35