unexpected end of regular expression

后端 未结 2 1400
旧巷少年郎
旧巷少年郎 2021-01-23 18:45

I want to get only the file name with extension from the path:

C:\\\\Users\\\\anandada\\\\workspace\\\\MyTestProject\\\\         


        
2条回答
  •  一生所求
    2021-01-23 19:38

    You need to double the doubled escapes again, or use a raw string instead:

    fileName = re.match("[^\\\\]*.c$",fileName)
    

    or

    fileName = re.match(r"[^\\]*.c$",fileName)
    

    otherwise first Python, then the regular expression compiler will interpret those backslashes, resulting in the ] being escaped:

    >>> print("[^\\]*.c$")
    '[^\]*.c$'
    

    Also see the Blackslash Plague section of the Python Regex HOWTO.

    Next, you need to be aware that re.match anchors to the start of the string. You'll probably want to use re.search() instead here. See the match() vs. search() section:

    The match() function only checks if the RE matches at the beginning of the string while search() will scan forward through the string for a match. It’s important to keep this distinction in mind.

    You may also want to escape the . in the .c part; . matches any character, so foobaric would also match; the i would satisfy the . pattern.

    The re.match() and re.search() functions return a match object, not the matched part of the string. You'll have to extract that part explicitly:

    fileName = re.search(r'[^\\]*\.c$', fileName).group()
    

    Demo:

    >>> import re
    >>> fileName = 'C:\\Users\\anandada\\workspace\\MyTestProject\\src\\OpenTest.c'
    >>> re.search(r'[^\\]*\.c$', fileName).group()
    'OpenTest.c'
    

提交回复
热议问题