简体   繁体   中英

Regex string inside 2 special characters without space

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 \\n ) 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 aZ of any lenght without space between two $

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