简体   繁体   中英

remove curly braces from string in python using regex

I want a regex expression to search 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)

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.

  [-\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 ...$

all together, these suggestions would make your line of code:

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

Just do a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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