正则表达式字符串里面有两个没有空格的特殊字符

I am trying to write a RegEx for preg_match_all in to match a string inside 2 $ symbols, like $abc$ but only if it doesn't have a space, for example, I don't need to match $ab c$.

I wrote this regex /[\$]\S(.*)[\$]/U and some variations but can't get it to work.

Thanks for your help guys.

Overview

Your regex: [\$]\S(.*)[\$]

  • [\$] - No point in escaping $ inside [] because it's already interpreted as the literal character. No point putting \$ inside [] because \$ is the escaped version. Just use one or the other [$] or \$.
  • \S(.*) Matches any non-whitespace character (once), followed by any character (except ) any number of times

Code

See regex in use here

\$\S+\$
  • \$ Match $ literally
  • \S+ Match any non-whitespace character one or more times
  • \$ Match $ literally

Usage

$re = '/\$\S+\$/';
$str = '$abc$
$ab c$';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

var_dump($matches);

I think this will suit your needs.

https://regex101.com/r/WgUwh9/1

\$([a-zA-Z]*)\$

It will match a-Z of any lenght without space between two $