\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]
>>> 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.
// 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();
}
这适用于提供的示例文本和预期结果:
我想James有什么发现,但他没有完全达到目的。你知道吗
你不应该用纯正则表达式来做这个。保持简单。首先,您应该通过
&
分割字符串:(当然,这是假设
someText
不能包含&
,但是如果可以的话,你有一个更难的问题。)然后我们需要
strip
去掉前面和后面的空白:现在我们可以使用正则表达式过滤掉不匹配的元素:
(请注意,
re.match
实际上返回的是Match
对象,而不是布尔对象。)这就是你想要的。缩短时间:
如果你想的话,你可以把它改成一行,但是看起来会更乱。你知道吗
现在对自己重复下面这句话3次:
如果我阅读正确,则您试图将每行中任意数量的“&;分隔项”捕获到捕获组中。你知道吗
对于纯正则表达式,这是不可能的。因为regex作为状态机运行,所以不能有任意数量的捕获组。任何给定的表达式都有固定数量的捕获组,这些捕获组可以或可能捕获任何内容。数字是由表达式决定的(基本上,你有多少套括号),不能改变。你知道吗
相反,您可以做一些类似的事情来捕获分隔符。因此,与其尝试匹配“someText 3”,不如在“&;上匹配并拆分。你知道吗
我不知道你用的是什么语言,下面是一些Javascript示例代码:
相关问题 更多 >
编程相关推荐