Home > Software engineering >  Regex: match between the fisrt and last occurrence of a specific character
Regex: match between the fisrt and last occurrence of a specific character

Time:08-19

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:

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!

CodePudding user response:

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
  • [\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.

A JavaScript version for non-ECMAScript 2018 compliant RegExp engines:

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]);
}

CodePudding user response:

I wouldn't use regex for this. For me at least, it is easier to just use 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?

  • Related