LSM
LSM

Reputation: 135

How to extract a word that could possibly be followed with another word

I want to extract [games, games, things, things] from the following array.

Today_games
Today_games_freq
Today_things
Today_things_freq

I have tried Today_(\w+)(?=_freq)? Which will give me the extra "freq"
And some other combinations, but I couldn't figure out how to get just after the first hyphen.

Upvotes: 1

Views: 22

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You can use

Today_(\w+?)(?:_freq)?$

See the regex demo. This matches Today_, then captures any one or more word chars (as few as possible) into Group 1 (with (\w+?)), and then (?:_freq)?$ matches an optional occurrence of a _freq substring and asserts the position at the end of string.

Or,

Today_([^\W_]+)

See this regex demo.

Here, Today_ is matched and the ([^\W_]+) pattern captures one or more alphanumeric chars into Group 1 (same as \w+ with _ subtracted from \w).

Upvotes: 1

Related Questions