Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex find word in the string

Tags:

regex

In general terms I want to find in the string some substring but only if it is contained there.

I had expression :

^.*(\bpass\b)?.*$ 

And test string:

high pass h3  

When I test the string via expression I see that whole string is found (but group "pass" not):

match : true groups count : 1   group : high pass h3  

But that I needed, is that match has 2 groups : 1: high pass h3 2: pass

And when I test, for example, the string - high h3, I still had 1 group found - high h3

How can I do this?

like image 655
baio Avatar asked Feb 19 '12 10:02

baio


People also ask

How do you search for a word in regex?

To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.

What does '$' mean in regex?

Literal Characters and Sequences For instance, you might need to search for a dollar sign ("$") as part of a price list, or in a computer program as part of a variable name. Since the dollar sign is a metacharacter which means "end of line" in regex, you must escape it with a backslash to use it literally.


1 Answers

Use this one:

^(.*?(\bpass\b)[^$]*)$ 
  1. First capture for the entire line.
  2. Second capture for the expected word.

Check the demo.

More explanation:

          ┌ first capture           |  ⧽------------------⧼ ^(.*?(\bpass\b)[^$]*)$   ⧽-⧼          ⧽---⧼    | ⧽--------⧼  |    |     |       └ all characters who are not the end of the string    |     |    |     └ second capture    |    └ optional begin characters 
like image 63
piouPiouM Avatar answered Sep 22 '22 06:09

piouPiouM