-1
st = """
    What kind of speCialist would we see for this?He also seems to have reactions to the red dye cochineal/carmine cialist,I like Cialist much
 """

在这里我只需要替换 Cialist 字符串(完全匹配),它最后也可能有逗号

不应抛出“专家*专家*”一词

我试过这个正则表达式。

 bold_string = "<b>"+"Cialist"+"</b>"
 insensitive_string = re.compile(re.escape("cialist"), re.IGNORECASE)
 comment = insensitive_string.sub(bold_string,st)

但它也抛出了字符串专家

你能建议我解决这个问题吗?

在 python 中替换十六进制字符的另一个问题。

 date_str = "28-06-2010\xc3\x82\xc2\xa008:48 PM"
 date_str = date_str.replace("\n","").replace("\t","").replace("\r","").replace("\xc3\x82\xc2\xa"," ")
 date_obj = datetime.strptime(date_str,"%d-%m-%Y %H:%M %p")
 Error: time data '08-09-2005\xc3\x82\xc2\xa010:18 PM' does not match format '%d-%m-%Y %H:%M %p'

在这里,我无法用空格替换十六进制字符以匹配日期时间模式。

你能帮忙解决这个问题吗?

4

3 回答 3

0

Use \b to match a word boundary. Then it becomes simples :)

import re

st = """
    What kind of speCialist would we see for this?He also seems to have reactions to the red dye cochineal/carmine cialist,I like Cialist much
 """

print re.sub(r'\bCialist\b', "<b>Cialist</b>", st)

For the second question you're missing a 0 at the end of your last replace string. Just add 0 and it works :)

date_str = "28-06-2010\xc3\x82\xc2\xa008:48 PM"
print date_str
date_str = date_str.replace("\n","").replace("\t","").replace("\r","").replace("\xc3\x82\xc2\xa0"," ")
print repr(date_str)
于 2012-06-29T19:09:25.327 回答
0

两个问题合二为一?

用单词边界替换你的正则表达式,所以它是re.sub(r'\bcialist\b', '', your_string, re.I)

于 2012-06-29T19:10:22.487 回答
0

对于您的第二个问题:

>>> re.sub(r'\\[a-zA-z0-9]{2}', lambda L: str(int(L.group()[2:], 16)), text)
'28-06-20101238212210008:48 PM'

要么为你的 strptime 重新组织它,要么让 strptime 解释它。

于 2012-06-29T19:26:21.223 回答