正则表达式更改字符串但不更改字符串+字符串2

时间:2017-01-27 15:27:50

标签: regex python-3.x notepad++

我有一个大文件,其中有几行包含localhost和localhost:portnumber(端口号不是常量。可以是4070,8080,9090)。我想将所有localhost或localhost:portnumber更改为localhost:但是我不想更改localhost:4080。简单的搜索和替换(localhost到localhost:4080)将localhost:portnumber更改为localhost:4080:portnumber。任何方法都可以使用regex.Preferbly in记事本++

示例输入:

https://localhost/subservice1 
https://localhost:4080/subservice1 
https://localhost:1090/subservice1 
https://localhost/subservice2

输出应该是

https://localhost:4080/subservice1 
https://localhost:4080/subservice1 
https://localhost:4080/subservice1 
https://localhost:4080/subservice2

3 个答案:

答案 0 :(得分:2)

这应该有用

REGEXP:适用于Python和Notepad ++

@relay(pattern: true)

<强> REPLACE:

(?:.*)(?:\blocalhost\/|localhost:4080\/)(.*)

PYTHON CODE:

https://localhost:4080/$1

<强> REGEXP:

<强> INPUT:

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

import re

regex = r"(?:.*)(?:\blocalhost\/|localhost:4080\/)(.*)"

test_str = ("https://localhost/subservice1 \n"
    "https://localhost:4080/subservice1 \n"
    "https://localhost/subservice1 \n"
    "https://localhost/subservice2")

subst = "https://localhost:4080/$1"

# 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.

<强>输出:

https://localhost/subservice1 
https://localhost:4080/subservice1 
https://localhost/subservice1 
https://localhost/subservice2

请参阅: https://regex101.com/r/kbPHd6/1

试用Python代码: http://ideone.com/yNoYzv

如果我帮助你,请将我标记为正确答案并投票。

<强>解释

https://localhost:4080/subservice1 
https://localhost:4080/subservice1 
https://localhost:4080/subservice1 
https://localhost:4080/subservice2

答案 1 :(得分:1)

替换://localhost/://localhost:4080/

答案 2 :(得分:1)

import re

text = [
    "https://localhost/subservice1",
    "https://localhost:4080/subservice1",
    "https://localhost/subservice1", 
    "https://localhost/subservice2"
]

regex = r'localhost/'
for x in text:
    result = re.sub(regex, "localhost:4080/", x)
    print(result)