我有一个字符串列表,即
slist = ["-args", "-111111", "20-args", "20 - 20", "20-10", "args-deep"]
我要从字符串中删除“-”,其中它是第一个字符,后跟字符串,而不是数字,或者如果在“-”之前有数字/字母,但它是字母之后,则应将'-'替换为空格
因此对于列表 slist ,我希望输出为
["args", "-111111", "20 args", "20 - 20", "20-10", "args deep"]
我尝试过
slist = ["-args", "-111111", "20-args", "20 - 20", "20-10", "args-deep"]
nlist = list()
for estr in slist:
nlist.append(re.sub("((^-[a-zA-Z])|([0-9]*-[a-zA-Z]))", "", estr))
print (nlist)
然后我得到输出
['rgs', '-111111', 'rgs', '20 - 20', '20-10', 'argseep']
答案 0 :(得分:1)
在这里,我们可能只想捕获起始-
之后的第一个字母,然后仅用该字母替换,也许用类似于以下内容的i
标志表达式:
^-([a-z])
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"^-([a-z])"
test_str = ("-args\n"
"-111111\n"
"20-args\n"
"20 - 20\n"
"20-10\n"
"args-deep")
subst = "\\1"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE | re.IGNORECASE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
const regex = /^-([a-z])/gmi;
const str = `-args
-111111
20-args
20 - 20
20-10
args-deep`;
const subst = `$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
如果不需要此表达式,可以在regex101.com中对其进行修改或更改。
jex.im可视化正则表达式:
答案 1 :(得分:1)
一个选项可能是进行两次替换。当仅以下字母时,请首先在开头匹配连字符:
^-(?=[a-zA-Z]+$)
在替换中,使用一个空字符串。
然后在组1中捕获1或更多次字母或数字,匹配-
,然后在组2中捕获1次以上的字母或数字。
^([a-zA-Z0-9]+)-([a-zA-Z]+)$
在替换中,使用r"\1 \2"
例如
import re
regex1 = r"^-(?=[a-zA-Z]+$)"
regex2 = r"^([a-zA-Z0-9]+)-([a-zA-Z]+)$"
slist = ["-args", "-111111", "20-args", "20 - 20", "20-10", "args-deep"]
slist = list(map(lambda s: re.sub(regex2, r"\1 \2", re.sub(regex1, "", s)), slist))
print(slist)
结果
['args', '-111111', '20 args', '20 - 20', '20-10', 'args deep']
答案 2 :(得分:1)
您可以使用
n
或
nlist.append(re.sub(r"-(?=[a-zA-Z])", " ", estr).lstrip())
结果:nlist.append(re.sub(r"-(?=[^\W\d_])", " ", estr).lstrip())
请参见Python demo。
['args', '-111111', '20 args', '20 - 20', '20-10', 'args deep']
模式在ASCII字母之前匹配连字符(-(?=[a-zA-Z])
在任何字母之前匹配连字符),并将匹配项替换为空格。由于-(?=[^\W\d_])
可能会在字符串的开头匹配,因此空格可能会出现在该位置,因此-
用于删除那里的空格。