简体   繁体   English

正则表达式和特殊字符本身

[英]regular expressions and a special character by itself

I want to replace the character & with and , but only when & is by itself. 我要替换的字符&and ,但只有当&是本身。 I try the following in Python 2.7.3 : 我在Python 2.7.3中尝试以下内容:

import re
re.sub('&', 'and', '& r&b')

I get and randb , but what I want is and r&b . 我得到了and randb ,但我想要的是and r&b

re.sub('\b&\b', 'and', '& r&b')

Doesn't work either. 也不起作用。 Any suggestions? 有什么建议? Also, what's the expression if I just wanted a unique combination of normal characters and special characters, like if I want a&b , but not a&bc ? 另外,如果我想要一个普通字符和特殊字符的独特组合,如果我想要a&b ,而不是a&bc ,那么表达式是什么?

Couldn't find the answer in similar questions, so thanks in advance! 在类似的问题中找不到答案,所以提前感谢!

Not knowing what "by itself" means. 不知道“本身”是什么意思。 Btw, nobody knows what that means in regex. 顺便说一句,没人知道正则表达式意味着什么。

Ror your specific example, Ror你的具体例子,

search (^| )&( |$) 搜索(^| )&( |$)
replace $1and$2 替换$1and$2

Don't know Python though. 不过不懂Python。

Edit: In Python 编辑:在Python中

import re
re.sub('(^| )&( |$)', r'\1and\2', '& r&b')

& is treated as a non word character. &被视为非单词字符。 So just use this simple substitution. 所以只需使用这个简单的替换。

Note: this will work for most usual cases in normal text. 注意:这适用于普通文本中的大多数常见情况。

>>> re.sub(r" & ", " and ", " & r&b")
' and r&b'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM