Home > database >  Regex take third element from a space separated list
Regex take third element from a space separated list

Time:09-23

I need help to create regular expression for getting the third element from a list such as

phrase1 phrase2 phrase3
phrase4 phrase5 phrase6

So the result should be

phrase3
phrase6

What is the regex for this?

CodePudding user response:

You may try the following find and replace, in regex mode:

Find:    ^.*[ ]
Replace: (empty)

Demo

The regex pattern ^.*[ ] will match everything from the start of the line up to, and including, the final space before the last word in the line. Then, we replace with nothing, thereby removing the first two (or more) words, leaving behind the third/final word.

CodePudding user response:

If you want to remove other items from the string and keep the 3rd one then use Tim Biegeleisen answer

If you want to match the 3rd item from the string then this answer will help you


You can use this regex:

^(?:(?:[^\s]  ){2})([^\s] )

with the g and m flags

Explanation:

In Words:

"Jump" over 2 items (item is any string that doesn't have whitespace in it) starting at the beginning of each line and match the 3rd item.

Whitespace is spaces, tabs, or line breaks

In Regex:

Let's break it into pieces:

  1. ^: start of the line (because we using the m flag
  2. [^\s] : match ant character is not a whitespace character (spaces, tabs, line breaks).
  3. (?:...): match but don't include in the matched result
  4. {2} require 2 items (of the (?:[^\s] ) regex)

Notes:

This will match the third item even if there are more items in line:

For example, it'll match phrase3 and phrase7 From:

phrase1 phrase2 phrase3 phrase4
phrase5 phrase6 phrase7
phrase8
  • Related