Paul Kroon
Paul Kroon

Reputation: 33

return text between two characters

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 :?

Upvotes: 3

Views: 137

Answers (3)

The fourth bird
The fourth bird

Reputation: 163632

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

Upvotes: 1

Pubudu Sitinamaluwa
Pubudu Sitinamaluwa

Reputation: 978

You already have achived that with your regex.

Positive Lookbehind : (?<=\t|,) check for comma or tab before start of match

First capturing group : ([a-z].*?) captures everything before : and after , or \t

Second capturing group : (:) captures :

Just extract the first captuaring group of your match.

Check regex demo

Upvotes: 0

codeandcloud
codeandcloud

Reputation: 55288

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

Upvotes: 1

Related Questions