使用python regex只获取文本

2024-07-07 07:04:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我怎样才能得到

The president of the United States appoints the cabinet members,
appointments are subject to Senate approval.

1. The president of the United States
appoints the cabinet members,

appointments are subject to Senate
approval.

(A) their

(B) with their
(C) because their
(D) but their

我开始我的模式,但它停止在'国家'。我也试着把 (A)的第一个圆括号作为字符串的结尾,但仍然不起作用

import re

regex = r'\d{1,}\.\s(\w.+)'

Tags: ofthetoareunitedsubjectmemberscabinet
1条回答
网友
1楼 · 发布于 2024-07-07 07:04:15

您可以在python中使用此正则表达式:

r'(?s)\A\d+\.\s+(.+?)(?=\n\()'

RegEx Demo

以下是正则表达式的详细信息:

  • (?s):在regex中启用单行模式
  • \A:输入的开始
  • \d+:匹配1+个数字
  • \.:匹配一个.
  • \s+:匹配1+个空格
  • (.+?):我们匹配的文本将有1+个字符,包括换行符,在组#1中捕获
  • (?=\n\():向前看以确保match具有换行符和(向前看

相关问题 更多 >