Python Regex to find a string in double quotes within a string

后端 未结 4 1311
自闭症患者
自闭症患者 2020-11-29 06:06

A code in python using regex that can perform something like this

Input: Regex should return \"String 1\" or \"String 2\" or \"String3\" 
Output: String 1,St         


        
4条回答
  •  野性不改
    2020-11-29 06:23

    The highly up-voted answer doesn't account for the possibility that the double-quoted string might contain one or more double-quote characters (properly escaped, of course). To handle this situation, the regex needs to accumulate characters one-by-one with a positive lookahead assertion stating that the current character is not a double-quote character that is not preceded by a backslash (which requires a negative lookbehind assertion):

    "(?:(?:(?!(?

    See Regex Demo

    import re
    import ast
    
    
    def doit(text):
        matches=re.findall(r'"(?:(?:(?!(?', ast.literal_eval(match))
    
    
    doit('Regex should return "String 1" or "String 2" or "String3" and "\\"double quoted string\\"" ')
    

    Prints:

    "String 1" => String 1
    "String 2" => String 2
    "String3" => String3
    "\"double quoted string\"" => "double quoted string"
    

提交回复
热议问题