Home > Net >  regex for matching string contains brackets with string between them only
regex for matching string contains brackets with string between them only

Time:06-08

I is there a regex that can match only the text inside brackets for example

  • (text) (text) (text) it should match
  • (text) normal text (text) shouldn't match
  • Normal text shouldn't match
  • Normal text (text) shouldn't match

I have tried this regex

/^(?![A-Za-z])(?:(\(.*?\)){1,})([A-Za-z])$/ 

it matches all the cases except when we have (text) normal text (text) it matches when it shouldn't

CodePudding user response:

This works:

^\s*(?:\([^()]*\)\s*) $

It matches any number of repetitions of (...) groups, with whitespace before and between them.

DEMO

CodePudding user response:

If you start the pattern with ( you don't need the negative lookahead (?![A-Za-z]), and you can omit ([A-Za-z])$ as that would match a single char at the end of the string.

You might use a pattern like matching chars a-z and whitespace chars:

^\([A-Za-z\s] \)(?:\s*\([A-Za-z\s] \))*$

Regex demo

Or more general using a negated character class:

^\([^()]*\)(?:\s*\([^()]*\))*$

Regex demo

  • Related