簡體   English   中英

正則表達式匹配字符串中的所有* texttexttext

[英]regex to match all *texttexttext in a string

我需要一個正則表達式,它將匹配所有以*開頭的字符串,直到遇到<

所以在這段文字中: bob went to the *store and he bought a toy and <then he went outside *and went to his car for <a ride.

它會匹配bob went to the *store and he bought a toy andand went to his car for

如果沒有“ <”,它將匹配所有行,直到行尾

嘗試這個:

<pre>
<?
$s = 'bob went to the *store and he bought a toy and <then he went outside *and went to his car for <a ride.';

preg_match_all("/\*([^<]+)/", $s, $matched); 
print_r($matched);
?>

輸出:

Array
(
    [0] => Array
        (
            [0] => *store and he bought a toy and 
            [1] => *and went to his car for 
        )

    [1] => Array
        (
            [0] => store and he bought a toy and 
            [1] => and went to his car for 
        )

)

應該是這樣的:

使用PHP:

preg_match_all("#\*(.+?)<#", $stringWithText, $matches, PREG_SET_ORDER);
$mCount = count($matches);

foreach ($matches as $match)
    echo "Matched: " . $match[1] . "<br/>";

如果要跳過結尾“ <”,請將表達式更改為#\\*(.+?)<?#並且如果要允許更改行,請使用以下標志:

preg_match_all("#\*(.+?)<#si", $stringWithText, $matches, PREG_SET_ORDER);

注意表達式后面的si標志

希望能幫助到你

嘗試\\*(.+?)<

您可以使用此工具來測試正則表達式: http : //gskinner.com/RegExr/

編輯要匹配到<或匹配到字符串的末尾,請使用:

\\*(.+?)[<|$.*]

我會用這樣的東西

(?<=\*).*?(?=<|$)

Regexr查看

(?<=\\*)是后面的字符,它不匹配任何字符,但可以確保之前的字符是*

.*? 匹配所有非貪婪的事物

(?=<|$)是向前看的字符,它不匹配任何字符,但可以確保后面的字符是<$ (行尾)==>使用m(多行)修飾符,否則$將僅匹配字符串的末尾,而不匹配行的末尾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM