繁体   English   中英

使用正则表达式从字符串中提取子字符串

[英]Extract Sub string from String using Regex

我有一个要求,我需要使用正则表达式从String中提取子字符串。

例如,这是我的示例数据:

Hello, "How" are "you" What "are" you "doing?"

从该示例数据中,我只需要提取第二和第四次出现双引号的数据。

我的要求是: you doing?

我尝试使用下面的正则表达式,但我无法按照我的要求进行提取。

"(.*?)"

我们可以使用re.findall然后对结果进行切片以获取第一个和第三个匹配项:

import re

string = 'Hello, "How" are "you" What "are" you "doing?"'
result = re.findall('".+?"', string)[1::2]

print(result)

此处,正则表达式会匹配双引号中包含的任意数量的字符,但会尝试匹配尽可能少的字符( 非贪婪匹配),否则我们将以单个匹配结尾, "How" are "you" What "are" you "doing?"

输出:

['"you"', '"doing?"']

如果你想他们不带引号结合起来,就可以使用str.strip沿str.join

print(' '.join(string.strip('"') for string in result))

输出:

you doing?

另一种方法是仅在"

result = string.split('"')[1::2][1::2]
print(result)

输出:

['you', 'doing?']

之所以可行,是因为如果用双引号将字符串分开,那么输出将如下所示:

  1. 第一个双引号之前的所有内容
  2. 第一个双引号之后和第二个双引号之前的所有内容
  3. 第二个双引号之后和第三个双引号之前的所有内容...

这意味着我们可以使用所有偶数元素来获取用引号引起来的元素。 然后,我们可以再次对结果进行切片以获得第二和第四结果。

仅Regex解决方案。 可能不是100%准确,因为它与第二个匹配项匹配,而不仅仅是第二和第四匹配,但它适用于示例。

"[^"]+"[^"]+("[^"]+")

JS演示:

 var str = 'Hello, "How" are "you" What "are" you "doing?"'; var regex = /"[^"]+"[^"]+("[^"]+")/g match = regex.exec(str); while (match != null) { // matched text: match[0] // match start: match.index // capturing group n: match[n] console.log(match[1]) match = regex.exec(str); } 

我们可以尝试使用re.findall提取所有引用的条款。 然后,仅使用结果列表中的偶数项来构建字符串:

input = "Hello, \"How\" are \"you\" What \"are\" you \"doing?\""
matches = re.findall(r'\"([^"]+)\"', input)
matches = matches[1::2]
output = " ".join(matches)
print(output)

you doing?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM