正则表达式重复字符串

2024-06-28 20:09:10 发布

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

我需要一个正则表达式为下面的文本。 我已经尝试了很多东西,但总是只匹配最后两组,或者匹配“someText 1&;someText 2&;someText 3&;作为一个组…”。。。你知道吗

someText 1 & someText 2 & someText 3
someText 1 & someText 2 & someText 3 & someText 4

我期待的是两个匹配:

匹配1:

  • 一些文本1
  • 一些文字2
  • 一些文字3

以及

匹配2:

  • 一些文本1
  • 一些文字2
  • 一些文字3
  • 一些文字4

Tags: 文本amp文字sometext
3条回答

这适用于提供的示例文本和预期结果:

\S+\s\d

\S+ match any non-white space character [^\r\n\t\f ]
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]

\s match any white space character [\r\n\t\f ]
\d match a digit [0-9]

我想James有什么发现,但他没有完全达到目的。你知道吗

你不应该用纯正则表达式来做这个。保持简单。首先,您应该通过&分割字符串:

>>> s = 'someText 1 & someText 2 & someText 3 & someText 4'
>>> s.split('&')
['someText 1 ', ' someText 2 ', ' someText 3 ', ' someText 4']

(当然,这是假设someText不能包含&,但是如果可以的话,你有一个更难的问题。)

然后我们需要strip去掉前面和后面的空白:

>>> s_clean = [i.strip() for i in s.split('&')]
>>> s_clean
['someText 1', 'someText 2', 'someText 3', 'someText 4']

现在我们可以使用正则表达式过滤掉不匹配的元素:

>>> import re
>>> [i for i in s_clean if re.match('.+\s+[0-9]+', i)]
['someText 1', 'someText 2', 'someText 3', 'someText 4']

(请注意,re.match实际上返回的是Match对象,而不是布尔对象。)

这就是你想要的。缩短时间:

s = 'someText 1 & someText 2 & someText 3 & someText 4'
s_clean = [i.strip() for i in s.split('&')]
result = [i for i in s_clean if re.match('.+\s+[0-9]+', i)]

如果你想的话,你可以把它改成一行,但是看起来会更乱。你知道吗

现在对自己重复下面这句话3次:

Regex is not the go to solution for all text processing problems.

如果我阅读正确,则您试图将每行中任意数量的“&;分隔项”捕获到捕获组中。你知道吗

对于纯正则表达式,这是不可能的。因为regex作为状态机运行,所以不能有任意数量的捕获组。任何给定的表达式都有固定数量的捕获组,这些捕获组可以或可能捕获任何内容。数字是由表达式决定的(基本上,你有多少套括号),不能改变。你知道吗

相反,您可以做一些类似的事情来捕获分隔符。因此,与其尝试匹配“someText 3”,不如在“&;上匹配并拆分。你知道吗

我不知道你用的是什么语言,下面是一些Javascript示例代码:

// Test input, as provided.
var inputString = "someText 1 & someText 2 & someText 3\nsomeText 1 & someText 2 & someText 3 & someText 4";

// Break up the lines. (Replace this with however you get your lines separated.)
var line_delimit = /[\n\r]+/;
var lines = inputString.split(line_delimit);

// Split each line on ampersands.
var group_delimit = /\s*&\s*/;
var matches = [];
lines.forEach(function(line){
    matches.push(line.split(group_delimit));
});

// Display.
for (var index in matches){
    console.log("Match " + index + ":");
    console.log(JSON.stringify(matches[index],null,2));
    console.log();
}

相关问题 更多 >