正则表达式匹配字符串中的所有* texttexttext

时间:2011-06-15 18:03:19

标签: php javascript html regex

我需要一个匹配所有以*开头的字符串的正则表达式,直到遇到<

所以在这个文本块中: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

如果没有“&lt;”它将匹配所有直到行的结尾

4 个答案:

答案 0 :(得分:2)

试试这个:

<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 
        )

)

答案 1 :(得分:1)

应该是这样的:

使用PHP:

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

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

如果你想跳过结尾“&lt;”将表达式更改为#\*(.+?)<?#,如果要允许换行,请使用以下标志:

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

注意si标志尾随表达式

希望有所帮助

答案 2 :(得分:1)

尝试\*(.+?)<

您可以使用此工具试用正则表达式:http://gskinner.com/RegExr/

修改 要保持与字符串末尾的< OR匹配,请使用:

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

答案 3 :(得分:1)

我会用这样的东西

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

Regexr

上查看

(?<=\*)是一个背后的外观,它不匹配任何字符,但它确保前面的字符是*

.*?匹配非贪婪的一切

(?=<|$)是展望未来,它不匹配任何字符,但它确保以下字符为<$(行结束)==&gt;使用m(多行)修饰符,否则$将只匹配字符串的结尾而不是行的结尾。