我有一个字符串列表
slist = ["-args", "-111111", "20-args", "20 - 20", "20-10", "args-deep"]我想从字符串中删除'-‘,其中是第一个字符,后面跟着字符串,但不是数字,或者如果在'-’之前有数字/字母表,但在它是字母之后,则应该用空格替换'-‘。
因此,对于list 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']发布于 2019-05-26 19:36:09
你可以用
nlist.append(re.sub(r"-(?=[a-zA-Z])", " ", estr).lstrip())或
nlist.append(re.sub(r"-(?=[^\W\d_])", " ", estr).lstrip())结果:['args', '-111111', '20 args', '20 - 20', '20-10', 'args deep']
见Python演示。
-(?=[a-zA-Z])模式在ASCII字母之前匹配连字符(-(?=[^\W\d_])在任何字母之前匹配连字符),并用空格替换匹配。由于-可能在字符串的开头匹配,所以空格可能出现在该位置,因此.lstrip()用于删除那里的空格。
发布于 2019-05-22 14:22:35
在这里,我们可能只想捕获起始-之后的第一个字母,然后仅用该字母替换它,可能使用类似于以下的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);
RegEx
如果不需要此表达式,则可以在regex101.com中修改或更改该表达式。
RegEx电路
jex.im可视化正则表达式:

发布于 2019-05-22 17:03:13
一种选择是做两次替换。当只有以下字母表时,首先匹配起始处的连字符:
^-(?=[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']https://stackoverflow.com/questions/56257376
复制相似问题