在这里,我们可能只想用捕获组包装第一部分:
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"(Technology libraries: )(.*)$"
test_str = "Technology libraries: Techlibhellohellohello"
subst = "\\1\\n\\2"
# 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.
这个 JavaScript 演示展示了捕获组的工作原理:
const regex = /(Technology libraries: )(.*)$/gm;
const str = `Technology libraries: Techlibhellohellohello`;
const subst = `\n$1\n$2`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
正则表达式
如果这不是您想要的表达方式,您可以在regex101.com 中修改/更改您的表达方式。
(Technology libraries: )(.*)
正则表达式电路
您还可以在jex.im 中可视化您的表达式:
如果您希望删除 : 和空格,您只需添加一个中间捕获组即可:
(Technology libraries)(:\s+)(.*)
Python 代码
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"(Technology libraries)(:\s+)(.*)"
test_str = ("Technology libraries: Techlibhellohellohello\n"
"Technology libraries: Techlibhellohellohello")
subst = "\\1\\n\\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.
JavaScript 演示
const regex = /(Technology libraries)(:\s+)(.*)/gm;
const str = `Technology libraries: Techlibhellohellohello
Technology libraries: Techlibhellohellohello`;
const subst = `\n$1\n$3`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
如果您想捕获“技术库”之前的空格,您可以简单地将它们添加到捕获组:
^(\s+)(Technology libraries)(:\s+)(.*)$
Python 测试
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"^(\s+)(Technology libraries)(:\s+)(.*)$"
test_str = (" Technology libraries: Techlibhellohellohello\n"
" Technology libraries: Techlibhellohellohello")
subst = "\\2\\n\\4"
# 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.
JavaScript 演示
const regex = /^(\s+)(Technology libraries)(:\s+)(.*)$/gm;
const str = ` Technology libraries: Techlibhellohellohello
Technology libraries: Techlibhellohellohello`;
const subst = `$2\n$4`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);