简体   繁体   English

使用正则表达式从python中的字符串中删除大括号

[英]remove curly braces from string in python using regex

I want a regex expression to search logger.error("pbType", 我想要一个正则表达式来搜索logger.error("pbType",

and exclude the ones with {} for example: 并排除带有{}的示例,例如:

logger.info("URL:\n\"{}\"\n",

this does not work for me - re.search('.*logger.*"[\\w.:-_()\\[\\]]*"\\s*,',line) 这对我re.search('.*logger.*"[\\w.:-_()\\[\\]]*"\\s*,',line)

It returns me lines with {} . 它以{}返回行。 Please help Thanks 请帮忙谢谢

Let's see how your current regular expression is parsing the line in question: 让我们看看您当前的正则表达式如何解析有问题的行:

.*|logger|      .*          |"|[\w.:-_()\[\]]*|"|\s*|,
  |      |                  | |               | |   |
  |logger|.info("URL:\n\"{}\|"|\n             |"|   |,

It's picking up the third quotation mark as the first one in the regular expression. 它在正则表达式中将第三个引号用作第一个引号。

To fix, you want to be sure that the ".*" s don't grab more than you want them to. 要解决此问题,您需要确保".*"不会比您希望的更多。

[^"\n]*logger[^"\n]*"[\w.:-_()\[\]]*"\s*,

Also, there are a few other mistakes in your current regex: 另外,您当前的正则表达式中还有其他一些错误:

[ :-_ ] includes all characters in the ascii range 58 to 95. if you want to include a minus sign in a character set, it must go first. [ :-_ ]包括ASCII范围在58到95之间的所有字符。如果要在字符集中包含减号,则必须排在前面。

  [-\w.:_()\[\]]

It's good style to use raw strings for regular expressions, as you know that backslashes will be backslashes instead of triggering an escape sequence. 将原始字符串用于正则表达式是一种很好的样式,因为您知道反斜杠将是反斜杠而不是触发转义序列。

 re.search(r'...', line)

You want to make sure the "\\s*, really gets the end of the string, there could be a \\",{} at the end you don't catch , so match an end of line in your regex ...$ 您要确保"\\s*,确实得到了字符串的末尾,可能有一个\\",{}没被抓住的末尾,因此请匹配正则表达式中的行尾...$

all together, these suggestions would make your line of code: 总之,这些建议将使您的代码行:

re.search(r'[^"\n]*logger[^"\n]*"[-\w.:-()\[\]]*"\s*,$', line)

Just do a if. 只要做一个if。 No need of regex - 无需正则表达式-

for i in l1:
    if not("{}" in i):
        l2.append(i)

l2 is the required result considering l1 is the list of your strings. 考虑到l1是您的字符串列表,l2是必需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM