正则表达式:在方括号之间删除,但仅在字符长度以下时删除 [英] Regex: delete between brackets, but only if below character length

查看:178
本文介绍了正则表达式:在方括号之间删除,但仅在字符长度以下时删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下字符串:

this is a text ( with parts in brackets ) . This is another string ( with a very long string between brackets that should not be removed because it is too long being over 100 characters )

所需的输出:

this is a text  . This is another string ( with a very long string between brackets that should not be removed because it is too long being over 100 characters )

我可以将方括号内容与(以将其替换为空字符串以将其删除的目标)相匹配.

I can match the bracket content with (with the goal to replace it with an empty string to remove it).

\s\(.+\)\s

现在,如果没有右括号,则正则表达式将删除大量文本.我想删除两个方括号之间的内容,但前提是长度是< 100个字符.我如何用正则表达式来做到这一点?我知道我需要一个前瞻性表达吗?感谢您的帮助!

Now, if there is no closing bracket, the regex deletes to much text. I would like to delete content between two brackets, but only if the length is < 100 chars. How an I do this with regex? I understand I would need a lookahead expression? I appreciate the help!

按照建议使用以下表达式不能作为解决方案:

Using the following expression, as suggested doesn't work as solution:

\s\(.+\){1,100}\s

推荐答案

使用

\s\([^()]{0,100}\)\s

请参见证明.在[^()]模式之后设置限制量词,它匹配parens以外的任何字符.

See proof. Set the limiting quantifier after the [^()] pattern, it matches any character other than parens.

示例代码:

import re

test_str = "this is a text ( with parts in brackets ) . This is another string ( with a very long string between brackets that should not be removed because it is too long being over 100 characters )"

print( re.sub(r"\s\([^()]{0,100}\)\s", "", test_str) )

输出:

this is a text. This is another string ( with a very long string between brackets that should not be removed because it is too long being over 100 characters )

这篇关于正则表达式:在方括号之间删除,但仅在字符长度以下时删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆