[英]How can I remove numbers at the end of words?
I want to remove numbers from a string which is just placed after a word without any space.我想从一个字符串中删除数字,该字符串只是放在一个没有任何空格的单词之后。 eg:
例如:
'Senku Ishigami is charecter from a manga series98 onging since 2017.'
should be:应该:
'Senku Ishigami is charecter from a manga series onging since 2017.'
I could remove detect the numbers with a regex '[az]+[0-9]+'
, But when I can't understand how can I remove it.我可以使用正则表达式
'[az]+[0-9]+'
删除检测数字,但是当我不明白如何删除它时。 I tried to remove it by just writing '[az]'
, as I thought it would work, but it is just printing '[az]'
as a string .我试图通过只写
'[az]'
来删除它,因为我认为它会起作用,但它只是将'[az]'
打印为 string 。
Here is the code:这是代码:
import re
text ='Senku Ishigami is charecter from a manga series98 onging since 2017.'
text = re.sub(r'[a-z]+[0-9]+', '[a-z]', text)
print(text)
output:输出:
Senku Ishigami is charecter from a manga [a-z] onging since 2017.
You might also use a capturing group capturing only a single char before matching 1+ digits.在匹配 1+ 数字之前,您还可以使用捕获组仅捕获单个字符。
In the replacement using group 1 using \\1
在使用组 1 的替换中使用
\\1
([a-z])\d+\b
import re
text ='Senku Ishigami is charecter from a manga series98 onging since 2017.'
text = re.sub(r'([a-z])\d+\b', r'\1', text)
print(text)
Output输出
Senku Ishigami is charecter from a manga series onging since 2017.
You can use您可以使用
import re
text ='Senku Ishigami is charecter from a manga series98 onging since 2017.'
text = re.sub(r'(?<=[a-z])\d+\b', '', text)
print(text) # => Senku Ishigami is charecter from a manga series onging since 2017.
See the regex demo and a Python demo .请参阅正则表达式演示和Python 演示。
Regex details正则表达式详情
(?<=[az])
- a location immediately preceded with a lowercase ASCII letter (?<=[az])
- 紧跟在小写 ASCII 字母前面的位置\\d+
- one or more digits \\d+
- 一位或多位数字\\b
- word boundary (the digits will only be matched at the end of a word). \\b
- 单词边界(数字只会在单词末尾匹配)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.