Regular expression optional match start/end of line

可紊 提交于 2021-02-07 20:53:23

问题


How do I optionally match the start ^ or end $ of a line in a regular expression.

For example:

/(?<=[\s\^])/ does not match starts with space character or start of line.

As requested my problem was in PHP matching the following.

$str = '**bold** **bold** **bold**';
echo preg_replace('/(?<=\s|^)\*\*(.+?)\*\*(?=\s|$)/', '<strong>\\1</strong>', $str);

My edge cases were the bold at the start and end of the string were not being matched. Some edge cases I came across with other variants were matching within strings, matching chains of asterisks, and countless other problems.

echo preg_replace('/(?<=^|\s|\>)[\*]{2,}(?=[^\s\*])(.+?)(?<=[^\s\*])[\*]{2,}(?=\s|\<|$)/', '<strong>\\1</strong>', $str);

回答1:


If you insist on matching after a whitespace character or the start of the line use an alternation (not the character class). Assuming your regex flavour supports alternations in lookbehind assertions.

/(?<=\s|^)\w+/m

but probably you are looking for a word boundary \b? They match on the start or end of a word. (Exactly on the change from a word character to a non word character or the other way round)

You should give us more information: the language, the input and the expected result (including corner cases).




回答2:


Just remove the anchors. Without the anchors, the regex will be matched anywhere in the string you are searching.



来源:https://stackoverflow.com/questions/15734322/regular-expression-optional-match-start-end-of-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!