我有以下字符串:
FIn 2021 did you contribute any money to the plan with USPS for example through payroll deductionsF ZsZ LExclude rollovers or cashouts from other retirement accounts or pension plans as new contributionsL
我想从这两个“F”之间的字符串中提取出这个问题,结果很清楚,如下所示:
In 2021 did you contribute any money to the plan with USPS for example through payroll deductions
我尝试过多个正则表达式,包括:
(?<=/)[^/'f']+(?=_[^'f']*$)
这并没有得到我想要的回应。
非常感谢事先给出的提示!
发布于 2022-08-18 15:40:37
您可以使用
(?<=\bF)[\w\W]*?(?=F\b)见regex演示。
详细信息
(?<=\bF) -与紧跟在字符串开头或前面有一个非字字符字符的位置匹配的正向查找。[\w\W]*? -任何零或多个字符尽可能少(?=F\b) --这是一种积极的展望,它需要一个F,后面跟着字符串的结尾,或者在当前位置的右侧有一个非字字符。非ECMAScript 2018+兼容的RegExp引擎的RegExp版本:
var re = /\bF([\w\W]*?)F\b/
var text = 'FIn 2021 did you contribute any money to the plan with USPS for example through payroll deductionsF ZsZ LExclude rollovers or cashouts from other retirement accounts or pension plans as new contributionsL';
var match = text.match(re);
if (match) {
console.log(match[1]);
}
发布于 2022-08-18 15:49:14
我不会用regex来做这个。至少对我来说,只使用String.indexOf更容易
var str = ...;
var idx = str.indexOf("F");
var idx2 = str.indexOf("F",idx + 1);
var substr = str.substring(idx + 1, idx2);我知道你说了regex,但我还是把它作为答案发布了,因为它使代码更加清晰。如果你想让我删除这个,让我知道?
https://stackoverflow.com/questions/73405875
复制相似问题