【问题标题】:regex to match all *texttexttext in a string正则表达式匹配字符串中的所有 *texttexttext
【发布时间】:2011-06-15 18:03:19
【问题描述】:

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

所以在这段文字中: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

如果没有“

【问题讨论】:

  • 根据您的描述,您的示例应该匹配store and he bought a toy and and went to his car for 。你是这个意思吗?

标签: php javascript html regex


【解决方案1】:

试试这个:

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

)

【讨论】:

  • 你可以让换行符也打破匹配吗?
【解决方案2】:

应该是这样的:

使用 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 标志

希望对你有帮助

【讨论】:

  • 我怎样才能让它匹配直到它找到一个“
【解决方案3】:

试试\*(.+?)&lt;

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

编辑 要保持与 &lt; 或字符串末尾的匹配,请使用:

\*(.+?)[&lt;|$.*]

【讨论】:

  • 它可以工作,但我如何修改以匹配即使最后没有
  • 这是否也会在新行停止匹配?
  • 不......你没有要求那个。 \*(.+?)[&lt;|\n|$|\r.*] - 将匹配来自 DOS 和 Linux 的换行符。但是,由于那里有很多 OR 子句,因此 * 和
【解决方案4】:

我会用这样的东西

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

Regexr这里查看

(?&lt;=\*) 是后面的样子,它不匹配任何字符,但它确保前面的字符是 *

.*? 匹配所有非贪婪的东西

(?=&lt;|$) 是向前看,它不匹配任何字符,但它确保后面的字符是 &lt;$(行结束)==> 使用 m(多行)修饰符,否则$ 将只匹配字符串的结尾而不是行的结尾。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-12
    • 2012-06-05
    • 2013-12-25
    • 1970-01-01
    相关资源
    最近更新 更多