Regex for managing escaped characters for items like string literals

后端 未结 6 862
别跟我提以往
别跟我提以往 2020-12-17 22:21

I would like to be able to match a string literal with the option of escaped quotations. For instance, I\'d like to be able to search \"this is a \'test with escaped\\\' val

6条回答
  •  伪装坚强ぢ
    2020-12-17 22:59

    Douglas Leeder's pattern ((?:^|[^\\])'(([^\\']|\\'|\\\\)*)') will fail to match "test 'test \x3F test' test" and "test \\'test' test". (String containing an escape other than quote and backslash, and string preceded by an escaped backslash.)

    cletus' pattern ((?) will fail to match "test 'test\\' test". (String ending with an escaped backslash.)

    My proposal for single-quoted strings is this:

    (?

    For both single-quoted or double-quoted stings, you could use this:

    (?

    Test run using Python:

    Doublas Leeder´s test cases:
    "''" matched successfully: ""
    " Example: 'Foo \' Bar'  End. " matched successfully: "Foo \' Bar"
    "'\''" matched successfully: "\'"
    " Example2: 'Foo \\' End. " matched successfully: "Foo \\"
    "not matched\''a'" matched successfully: "a"
    "\''a'" matched successfully: "a"
    
    cletus´ test cases:
    "'testing 123'" matched successfully: "testing 123"
    "'testing 123\\'" matched successfully: "testing 123\\"
    "'testing 123" didn´t match, as exected.
    "blah 'testing 123" didn´t match, as exected.
    "blah 'testing 123'" matched successfully: "testing 123"
    "blah 'testing 123' foo" matched successfully: "testing 123"
    "this 'is a \' test'" matched successfully: "is a \' test"
    "another \' test 'testing \' 123' \' blah" matched successfully: "testing \' 123"
    
    MizardX´s test cases:
    "test 'test \x3F test' test" matched successfully: "test \x3F test"
    "test \\'test' test" matched successfully: "test"
    "test 'test\\' test" matched successfully: "test\\"
    

提交回复
热议问题