首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Regex:特定字符的fisrt和最后一次出现的匹配

Regex:特定字符的fisrt和最后一次出现的匹配
EN

Stack Overflow用户
提问于 2022-08-18 15:38:17
回答 2查看 28关注 0票数 0

我有以下字符串:

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']*$)

这并没有得到我想要的回应。

非常感谢事先给出的提示!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-08-18 15:40:37

您可以使用

代码语言:javascript
复制
(?<=\bF)[\w\W]*?(?=F\b)

regex演示

详细信息

  • (?<=\bF) -与紧跟在字符串开头或前面有一个非字字符字符的位置匹配的正向查找。
  • [\w\W]*? -任何零或多个字符尽可能少
  • (?=F\b) --这是一种积极的展望,它需要一个F,后面跟着字符串的结尾,或者在当前位置的右侧有一个非字字符。

非ECMAScript 2018+兼容的RegExp引擎的RegExp版本:

代码语言:javascript
复制
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]);
}

票数 2
EN

Stack Overflow用户

发布于 2022-08-18 15:49:14

我不会用regex来做这个。至少对我来说,只使用String.indexOf更容易

代码语言:javascript
复制
var str = ...;
var idx = str.indexOf("F");
var idx2 = str.indexOf("F",idx + 1);
var substr = str.substring(idx + 1, idx2);

我知道你说了regex,但我还是把它作为答案发布了,因为它使代码更加清晰。如果你想让我删除这个,让我知道?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73405875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档