正则表达式python
对不起,如果标题有点模糊,我现在想不出更好的了 我正在努力为我的一个小测试找到正确的正则表达式: 输入和输出:正则表达式python,python,regex,Python,Regex,对不起,如果标题有点模糊,我现在想不出更好的了 我正在努力为我的一个小测试找到正确的正则表达式: 输入和输出: "Hello" --------------> ("Hello", "") "How are you doing?" -> ("How", "are you doing?") "" -------------------> ("", "") "!h0w are you?" ------> ("!h0w", "are you?") "#" ------------
"Hello" --------------> ("Hello", "")
"How are you doing?" -> ("How", "are you doing?")
"" -------------------> ("", "")
"!h0w are you?" ------> ("!h0w", "are you?")
"#" ------------------> ("#", "")
":::::::" ------------> (":::::::", "")
到目前为止,最接近的正则表达式是“(\.?)(.*?)((\s+?)(.*?$)”
,但它提供了许多不需要的数据,如
regex = lambda text: re.search("(\.?)(.*?)((\s+?)(.*?)$|$)", text).groups()
# Input and Output
regex("Hello") --------------> ('', 'Hello', '', None, None)
regex("How are you doing?") -> ('', 'How', ' are you doing?', ' ', 'are you doing?')
regex("") -------------------> ('', '', '', None, None)
regex("!h0w are you?") ------> ('', '!h0w', ' are you?', ' ', 'are you?')
regex("#") ------------------> ('', '#', '', None, None)
regex(":::::::") ------------> ('', ':::::::', '', None, None)
None
我更喜欢的是:
x,y=re.search(模式,字符串).groups()
如果这是不可能的,有人可以改进现有的正则表达式吗?我一直在努力改进它一点,但我似乎不能使它更好
无法使用str.split进行此操作,试图找出如何使用正则表达式。正则表达式执行此操作的方法基本上仍然是
str.split
,但使用正则表达式split
:
parts = re.split(r'\s+', text, maxsplit=1)
part1 = parts[0]
part2 = '' if len(parts) == 1 else parts[1]
\s+
匹配任何空白maxsplit=1
表示仅在模式第一次出现时分割。请注意,这可能无法按您所希望的方式处理前导或尾随空格。看起来您只是在一个可选空格之前和之后拆分为多个部分:
import re
regex = lambda text: re.match(r'(\S*)(?:\s*)(.*)', text).groups()
x, y = regex('this that')
结果如下:
regex("Hello")
('Hello', '')
regex("How are you doing?")
('How', 'are you doing?')
regex("")
('', '')
regex("!h0w are you?")
('!h0w' ,'are you?')
regex("#")
('#', '')
regex(":::::::")
(':::::::', '')
基本上:
是一个文本字符串,您可以在其中使用r'string here'
,而无需对其进行双重转义\
匹配每个非空格字符,直到第一个空格。如果第一个空格前没有字符,则返回(\S*)
(而不是”
)None
匹配第一段空白,但开头的(?:\s*)
使其成为不匹配的组,因此它不是?:
组()输出的一部分
- 结尾处的
捕获第一个空格后的所有剩余字符。如果空格后没有字符,或者没有空格,则返回(.*)
(而不是”
)None