开发者

How can I use regex for all words beginning with : punctuation?

开发者 https://www.devze.com 2023-03-20 21:55 出处:网络
How can I use regex for all words beginning with : punctuation? This gets all words beginning with a: \\ba\\w*\\b

How can I use regex for all words beginning with : punctuation?

This gets all words beginning with a:

\ba\w*\b

The minute I change 开发者_开发技巧the letter a to :, the whole thing fails. Am I supposed to escape the colon, and if so, how?


\b matches between a non-alphanumeric and an alphanumeric character, so if you place it before :, it only matches if there is a letter/digit right before the colon.

So you either need to drop the \b here or specify what exactly constitutes a boundary in this situation, for example:

(?<!\w):\w*\b

That would ensure that there is no letter/digit/underscore right before the :. Of course this presumes a regex flavor that supports lookbehind assertions.


The problem is that \b won't match the start of a word when the word starts with a colon :, because colon is not a word character. Try this:

(?<=:)\w*\b

This uses a (non-capturing) look-behind to assert that the previous character is a colon.

0

精彩评论

暂无评论...
验证码 换一张
取 消