0

I have read up on other questions/answers that get the text between square brackets - but what if I only want to get those brackets with specific text.

For example, the string I have is in the following format:

{this is a}{string with text}{i want this bracket}{only}

I want to extract all of the {i want this bracket} by searching upon want and bracket only. The i and this could be random text, example {gjddnsgwantjgnsagjbracket}

I can split them up into groups by doing the following:

/\{(.*?)\}/g

But I cannot for the love of me search within said capture groups to extract the bracket I want.

Jonathan Davies
  • 853
  • 2
  • 12
  • 23

2 Answers2

1

This should work...

$ echo '{i want this bracket}' | grep -E '{[^}]*want[^}]*bracket[^}]*}'
{i want this bracket}

$ echo '{gjddnsgwantjgnsagjbracket[^}]*}' | grep -E '{[^}]*want[^}]*bracket[^}]*}'
{gjddnsgwantjgnsagjbracket}
Bill
  • 12,022
  • 4
  • 34
  • 54
  • Thanks for the prompt response, @Bill. How does this cope if `want` is in another bracket as well as it's own with `bracket`? Will it return two brackets? If so, is there a way to make it only return the bracket with `want and bracket` in? I hope this makes sense. – Jonathan Davies Oct 23 '17 at 23:07
  • It will not match words without both words in them. e.g. `$ echo '{gjddnsgwantjgnsagjb}' | grep -E '{[^}]*want[^}]*bracket}'` results in no match. – Bill Oct 24 '17 at 04:26
1

Try this Regex:

{(?=[^}]*want)(?=[^}]*bracket)[^}]+}

Click for Demo

Explanation:

  • { - matches { literally
  • (?=[^}]*want) - positive lookahead to validate for the presence of want before the }
  • (?=[^}]*bracket) - positive lookahead to validate for the presence of want before the }
  • [^}]+ - matches 1+ occurrences of any character that is not a }
  • } - matches a } literally
Gurmanjot Singh
  • 8,936
  • 2
  • 17
  • 37