esryl
esryl

Reputation: 189

Regular expression optional match start/end of line

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.

My problem was in PHP matching the following.

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

My edge cases that 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);

Upvotes: 6

Views: 10556

Answers (2)

stema
stema

Reputation: 92976

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

Upvotes: 12

Femaref
Femaref

Reputation: 61437

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

Upvotes: 0

Related Questions