dongxun1978 2018-01-17 20:27
浏览 68
已采纳

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

I am trying to write a RegEx for preg_match_all in php 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.

  • 写回答

2条回答 默认 最新

  • dongpaozhi5734 2018-01-17 20:34
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?