1

I have the following regex:

{thing:([^}]*)}

This matches '{thing:' and '}' exactly, and allows anything !} in the middle.

In C#, I was able to grab only the stuff in the middle with the following:

regex.Matches(stringToCheckForMatches).Cast<Match>().Select(x => x.Groups[1].Value);

Is there an equivalent way to grab that middle stuff in TypeScript? Note also that stringToCheckForMatches can contain multiple instances of the {thing:} keyword (with any middle-stuff content).

For instance, I would want this:

'fooBar/{thing:hi}{thing:hello}'

To return (in an array/list preferably) just this:

hi
hello

Alternatively, if you cannot access .match captures in TypeScript (I am honestly not sure), is there a way to change the regex to something that captures only content after '{thing:' and before '}'? That would also work.

1 Answer 1

1

Splitting by the regular expression results in ["fooBar/", "hi", "", "hello", ""] :

console.log( 'fooBar/{thing:hi}{thing:hello}'.split(/{thing:([^}]*)}/) );

and filter can be used to get the odd elements:

console.log( 'fooBar/{thing:hi}{thing:hello}'.split(/{thing:([^}]*)}/).filter((_, i) => i & 1) );

or

console.log( 'fooBar/{thing:hi}{thing:hello}'.split(/.*?{thing:(.*?)}.*?/).filter(Boolean) );


Alternative without regular expression:

var str = 'fooBar/{thing:hi}{thing:hello}'

console.log( str.split('{thing:').slice(1).map(s => s.split('}')[0]) );

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.