问题:[^\/] 匹配任何不同于正斜杠的字符。 \w 不匹配斜线。
使用
pattern = r"(?=(?:[^/]*/)?[^/]*$)[\w/]{1,4}(\n[\w/]{1,4})?"
return bool(re.fullmatch(pattern, word))
见proof。
说明
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
[^/]* any character except: '/' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
/ '/'
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
[^/]* any character except: '/' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
$ before an optional \n, and the end of
the string
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
[\w/]{1,4} any character of: word characters (a-z, A-
Z, 0-9, _), '/' (between 1 and 4 times
(matching the most amount possible))
--------------------------------------------------------------------------------
( group and capture to \1 (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
\n '\n' (newline)
--------------------------------------------------------------------------------
[\w/]{1,4} any character of: word characters (a-z,
A-Z, 0-9, _), '/' (between 1 and 4 times
(matching the most amount possible))
--------------------------------------------------------------------------------
)? end of \1 (NOTE: because you are using a
quantifier on this capture, only the LAST
repetition of the captured pattern will be
stored in \1)
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
Python code:
import re
strings = ["EYE", "EYE\n1/2", "SOFT\nTISS", "BLAD\n2"]
for s in strings:
print(bool(re.fullmatch(r'(?=(?:[^/]*/)?[^/]*$)[\w/]{1,4}(\n[\w/]{1,4})?', s)))