Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return text between two characters

Tags:

regex

My regex is matching a string like between a tab or comma and a colon.

(?<=\t|,)([a-z].*?)(:)

This returns a string: app_open_icon:

I would like the regex to remove the : appended and return app_open_icon only.

How should I chnage this regex to exclude :?

like image 242
Paul Kroon Avatar asked Jul 08 '26 16:07

Paul Kroon


2 Answers

Try (?<=\t|,)[a-z].*?(?=:)

const regex = /(?<=\t|,)[a-z].*?(?=:)/;
const text='Lorem ipsum dolor sit amet,app_open_icon:consectetur adipiscing...';
const result = regex.exec(text);
console.log(result);
like image 80
naveen Avatar answered Jul 11 '26 10:07

naveen


You don't have to use lookarounds, you can use a capture group.

[\t,]([a-z][^:]*):
  • [\t,] Match either a tab or comma
  • ( Capture group 1
    • [a-z][^:]* Match a char in the range a-z and 0+ times any char except :
  • ) Close group 1
  • : Match literally

Regex demo

const regex = /[\t,]([a-z][^:]*):/;
const str = `,app_open_icon:`;
const m = str.match(regex);
if (m) {
  console.log(m[1]);
}

To get a match only using lookarounds, you can turn the matches into lookarounds, and omit the capture group 1:

(?<=[\t,])[a-z][^:]*(?=:)

Regex demo

const regex = /(?<=[\t,])[a-z][^:]*(?=:)/;
const str = `,app_open_icon:`;
const m = str.match(regex);
if (m) {
  console.log(m[0]);
}
like image 30
The fourth bird Avatar answered Jul 11 '26 12:07

The fourth bird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!