简体   繁体   中英

regex to match string but not substring

I have this regex /\\$([^:\\n]+)/ and the following strings

  1. gid$gid::
  2. $gid::
  3. ::$gid
  4. bar$:$gid:f$oo

currently running the regex on each string independently , I get these matches

  1. gid
  2. gid
  3. gid
  4. [ gid , oo ]

I need to alter the regex so there are no matches in number 1 and only one match in number 4 - the middle $gid . In other words, it only matches strings starting with $ that start at the beginning of the string or immediately after a colon .

Thank you in advance!

You may find other examples that further restrict what you need, but this seems to work as you describe:

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

Working here https://regex101.com/r/HGtNw1/1

I ended up using (php)

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

the m options and the implied g options (by _all in the function) were key to getting the answer I needed.

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

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