开发者

Trying to match '#' in a text

I'm trying to match a "#" followed by letters if and only if it's preceded by newline, whitespace or is the first character in a string. The first two I've done, but I'开发者_开发知识库m having a hard time matching if it's the first character in a string. I'm trying to find a use for '\A', but it doesn't work to just add it to the class containing newline and whitespace. What have I missed?

The regular expression I've come up with so far is:

from re import findall, escape
from string import punctuation, whitespace

NEWLINE = """\r\n?|\n"""
INVALID_TAG_CHARACTERS = escape(punctuation.replace('-', '').replace('_', '') + whitespace)
VALID_TAGS = r'[\s%s]+#[^%s]+' % (NEWLINE, INVALID_TAG_CHARACTERS)
tags = findall(VALID_TAGS, text)


I think this is what you're looking for:

result = re.findall("(?:^|\s)(#[a-zA-Z]+)", text, re.MULTILINE)

The (?:^|\s) is a set of non-grouping parentheses (we don't want this part in our results). With the multiline flag, it will match the beginning of the string, or a preceding newline or whitespace. The next group is your 'tag,' I believe. If it's other than letters following the #, you'll have to fiddle with that second group.


Turn on the multi-line flag, so ^ matches the position after a newline, then just use:

re.compile(r"(?m)^\s*#") # includes the flag for multi-line

Or

re.compile(r"(?m)^\s*#.*$")

to get the full line (with dot matching newline mode disabled).

For the "first character in string", that depends on what a string is defined as - you may need to use a full parser for this, rather than a single regex.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜