![](/img/trans.png)
[英]Dollar Sign “\$” in Regular Expressions with word boundaries “\b” (PHP / JavaScript)
[英]find word with dollar sign
我試圖使用正則表達式查找第一個字符($)的單詞,但無法使其正常工作。 我試過了:
$string = '$David is the cool, but $John is not cool.';
preg_match('/\b($\w+)\b/', $string, $matches);
我試圖轉義$,但仍然無法正常工作:
preg_match('/\b(\$\w+)\b/', $string, $matches);
我想提取[$ David,$ John]。
請幫忙!
\\b
在非單詞字符和$
(另一個非單詞字符)之間不匹配。
\b
相當於
(?<!\w)(?=\w)|(?<=\w)(?!\w)
所以你可以使用
/(?<!\w)(\$\w+)\b/
也就是說,可能沒有理由檢查$
之前的內容,因此應執行以下操作:
/(\$\w+)\b/
此外,該\\b
將始終匹配,因此可以省略。
/(\$\w+)/
此外,您似乎想要所有匹配項。 為此,您需要使用preg_match_all
而不是preg_match
。
如前所述,不需要使用單詞邊界和非單詞邊界,但是要匹配其他變量,則必須使用preg_match_all :
$string = '$David is the cool, but $John is not cool.';
preg_match_all('/(\$\w+)/', $string, $matches);
print_r($matches);
輸出:
Array
(
[0] => Array
(
[0] => $David
[1] => $John
)
[1] => Array
(
[0] => $David
[1] => $John
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.