[英]Remove #{word} from a string using regex (python)
I'm not familiar with regex, and it would be great to have some help. 我对正则表达式不熟悉,因此获得一些帮助将是很棒的。
I have a string: string = "You get #{turns} guesses."
我有一个字符串:
string = "You get #{turns} guesses."
and I would like to remove #{turns}
in order to have string = "You get guesses."
并且我想删除
#{turns}
以便使string = "You get guesses."
I've tried it with: 我已经尝试过:
string = re.sub(re.compile('#{.*?}'),"",string)
Any suggestions? 有什么建议么?
Your code works, except that it does not remove a sufficient amount of spaces and that compilation is rather useless if you only use it once: 您的代码可以工作,除了它不会删除足够的空格,并且如果只使用一次,则编译是毫无用处的:
>>> string = "You get #{turns} guesses."
>>> string = re.sub(re.compile('#{.*?}'),"",string)
>>> string
'You get guesses.'
So you probably want to compile the regex once, and then use it, and you better alter it to - for instance - remove tailing spaces: 因此,您可能希望先编译一次正则表达式,然后再使用它,最好将其更改为-例如,删除尾部空格:
rgx = re.compile('#{.*?}\s*')
string = rgx.sub('',string)
Note the \\s*
which will match with an arbitrary amount of spaces after the tag, and thus remove these as well: 请注意
\\s*
,它将与标记后的任意数量的空格匹配,因此也将其删除:
>>> string = "You get #{turns} guesses."
>>> rgx = re.compile('#{.*?}\s*')
>>> string = rgx.sub('',string)
>>> string
'You get guesses.'
In case it is one word between the curly brackets ( {}
), you better use \\w
to exclude spaces: 如果在大括号(
{}
)之间是一个单词 ,则最好使用\\w
排除空格:
rgx = re.compile('#{\w*}\s*')
For this specific question you can also do it like so: 对于这个特定的问题,您也可以这样做:
import re
string = "You get #{turns} guesses."
re.sub(r'#\S+ ', r'', string)
Output: 输出:
'You get guesses.'
Regex: 正则表达式:
'#\\S+ '
Match # and match as many non space characters and a single space. '#\\S+ '
匹配#并匹配多个非空格字符和一个空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.