用于以特殊模式添加空格的正则表达式

快速说明:我知道降价解析器不关心这个问题。这是为了 md 文件中的视觉一致性以及实验。


样品:


# this

##that

###or this other

目标:阅读每一行,如果 Markdown 标题在井号/主题标签后面没有空格,则添加一个,使其看起来像:


# this

## that

### or this other

我的非正则表达式尝试:


function inelegantFunction (string $string){

    $array = explode('#',$string);

    $num = count($array);

    $text = end($array);

    return str_repeat('#', $num-1)." ".$text;

}


echo inelegantFunction("###or this other"); 

// returns  ### or this other

这有效,但它没有机制来匹配七个“#”的不太可能的情况。


无论功效如何,我都想弄清楚如何在 php 中使用正则表达式(如果重要的话,也可能是 javascript)。


手掌心
浏览 140回答 2
2回答

临摹微笑

我猜一个带有正确字符列表边界的简单表达式可能在这里工作,也许:(#)([a-z])如果我们可能有更多字符,我们可以简单地将它添加到[a-z].测试$re = '/(#)([a-z])/m';$str = '#this##that###that### or this other';$subst = '$1 $2';$result = preg_replace($re, $subst, $str);echo "The result of the substitution is ".$result;
打开App,查看更多内容
随时随地看视频慕课网APP