使用正则表达式匹配直到某个模式
我有一个文本文件,里面有一些文字,内容如下:
txt = "java.awt.GridBagLayout.layoutContainer"
我想要提取出“GridBagLayout”这个类名之前的所有内容。
我尝试过一些方法,但我不知道怎么去掉这个"."。
txt = re.findall(r'java\S?[^A-Z]*', txt)
结果我得到的是:"java.awt."
而我想要的结果是:"java.awt"
有没有什么建议可以帮我解决这个问题?
相关问题:
3 个回答
0
让你的匹配规则找到一个句点后面跟着一个大写字母:
'(java\S?[^A-Z]*?)\.[A-Z]'
捕获组中的内容就是你想要的结果。
0
这个看起来可以满足你的需求,使用了 re.findall():(java\S?[^A-Z]*)\.[A-Z]
19
不使用捕获组的情况下,你可以用前瞻(就是那个 (?= ... ) 的东西)。
java\s?[^A-Z]*(?=\.[A-Z]) 这个表达式应该能抓到你想要的所有内容。下面是它的详细解释:
java //Literal word "java"
\s? //Match for an optional space character. (can change to \s* if there can be multiple)
[^A-Z]* //Any number of non-capital-letter characters
(?=\.[A-Z]) //Look ahead for (but don't add to selection) a literal period and a capital letter.