简体   繁体   English

正则表达式:匹配特定字符的第一次和最后一次出现

[英]Regex: match between the fisrt and last occurrence of a specific character

I have the following string:我有以下字符串:

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

I would like to extract the question out of this string between the two "F"s, with a clean result such as this:我想从两个“F”之间的这个字符串中提取问题,得到一个干净的结果,例如:

In 2021 did you contribute any money to the plan with USPS for example through payroll deductions

I have tried multiple regex expressions including:我尝试了多种正则表达式,包括:

(?<=/)[^/'f']+(?=_[^'f']*$)

which did not yield the response I wanted.这没有产生我想要的回应。

Many thanks for any hints in advance!非常感谢您提前提供的任何提示!

You can use您可以使用

(?<=\bF)[\w\W]*?(?=F\b)

See the regex demo .请参阅正则表达式演示

Details :详情

  • (?<=\bF) - a positive lookbehind that matches a location that is immediately preceded with an F that is either at the start of string or preceded with a non-word char (?<=\bF) - 一个正向的向后查找,它匹配紧接在 F 前面的位置,该F位于字符串的开头或前面有一个非单词字符
  • [\w\W]*? - any zero or more chars as few as possible - 尽可能少的任何零个或多个字符
  • (?=F\b) - a positive lookahead that requires an F followed with end of string or a non-word char immediately to the right of the current location. (?=F\b) - 一个正向前瞻,需要一个F后跟字符串结尾或紧跟当前位置右侧的非单词字符。

A JavaScript version for non-ECMAScript 2018+ compliant RegExp engines: JavaScript 版本,用于非 ECMAScript 2018+ 兼容的 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]); }

I wouldn't use regex for this.我不会为此使用正则表达式。 For me at least, it is easier to just use String.indexOf至少对我来说,使用 String.indexOf 更容易

var str = ...;
var idx = str.indexOf("F");
var idx2 = str.indexOf("F",idx + 1);
var substr = str.substring(idx + 1, idx2);

I know you said regex, but I posted this as an answer anyway because it makes the code clearer.我知道您说的是正则表达式,但无论如何我还是将其发布为答案,因为它使代码更清晰。 If you want me to delete this, let me know?如果你想让我删除这个,请告诉我?

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

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