正则表达式用于替换字母数字字符串中间的数字,而不是末尾的数字

时间:2019-05-23 18:33:26

标签: python regex

我有以下字符串:

aaaaaaa0aaa
bbbbbbb0bbbbbb
cccccc 2.0

我需要用某些字符(例如“ x”)替换前2个字符串中间的0。如果我使用正则表达式r'[0].',则从前2个字符串中选择“ 0a”和“ 0b”。我如何才能仅从前2个字符串中选择“ 0”,同时避免最后一个字符串中的“ 0”

5 个答案:

答案 0 :(得分:4)

您可以使用\B在匹配的0周围声明非单词边界:

\B0\B

演示:https://regex101.com/r/8GGONp/1

>>> import re
>>> s = '''aaaaaaa0aaa
... bbbbbbb0bbbbbb
... cccccc 2.0'''
>>> print(re.sub(r'\B0\B', 'x', s))
aaaaaaaxaaa
bbbbbbbxbbbbbb
cccccc 2.0
>>>

答案 1 :(得分:1)

在这里,我们可以收集字母,然后将一个字母保留为我们要替换的数字的左边界,然后为了安全起见在数字之后添加另一个字母,并继续捕获字符串末尾的字母,最后替换数字与$1x$3

(.+[a-z])([0-9]+)([a-z].+) 

DEMO

enter image description here

RegEx

如果不需要此表达式,可以在regex101.com中对其进行修改或更改。

RegEx电路

jex.im可视化正则表达式:

enter image description here

测试

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(.+[a-z])([0-9]+)([a-z].+)"

test_str = ("aaaaaaa0aaa\n"
    "bbbbbbb0bbbbbb\n"
    "cccccc 2.0")

subst = "\\1x\\3"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

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])([0-9]+)([a-z].+)/gm;
const str = `aaaaaaa0aaa
bbbbbbb0bbbbbb
cccccc 2.0`;
const subst = `$1x$3`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

答案 2 :(得分:1)

只需进行r'0(?=.)'中的简单正向查找即可。使用python

import re

s = '''aaaaaaa0aaa
bbbbbbb0bbbbbb
cccccc 2.0'''

re.sub(pattern=r'0(?=.)', string=s, repl='x')

Out[743]: '\n    aaaaaaaxaaa\n    bbbbbbbxbbbbbb\n    cccccc 2.0'

答案 3 :(得分:0)

这取决于您想要变得多么贪婪。更严格的方法更好,但是假设您始终想定位[a-zA-Z](0)[a-zA-Z],这样的0效果很好,并且它会被字母字符(a-zA-Z)明确包围。

您可以试用它,并在此处查看它的工作原理:https://regex101.com/r/0UYSvp/1

答案 4 :(得分:0)

只需匹配0:try{ const renameFilesPromise = renameFiles(); renameFilesPromise.then({ <-- then is a callback when promise is resolved console.log("do other stuff"); }) } catch(){ } const renameFiles = (path) => { return new Promise(resolve => { console.log("Renaming files..."); fs.readdirSync(path).forEach(file) => { // if file is a directory ... let newPath = path.join(path, file); resolve( renameFiles(newPath) ); // <- recursion here! // else rename file ... } resolve(); }) 之后的任何内容,并替换为0(.)

只有在其后有一个字符时,它才会与零匹配,并将其替换为“ x”和该字符。

请参阅regex101解决方案