leemon
leemon

Reputation: 1061

Regex to match strings inside brackets with no spaces around

I'm using the following regex to match strings inside brackets:

\((.*?)\)

But this matches this:

(word)

and this too:

( word )

I need to modify it to only match the first case: words inside brackets with no spaces around: (word)

Any ideas?

Thanks in advance

Upvotes: 1

Views: 5062

Answers (3)

codeonly
codeonly

Reputation: 1

Word Boundaries

\(\b[^)]+\b\)

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

You can use this pattern:

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

[^\s()] ensures that the first character isn't a whitespace or brackets (and make mandatory at least one character).

(?: [^()]* [^\s()] )? is optional. if it matches, the same character class ensures that the last character isn't a whitespace.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Use lookahead/lookbehind to disallow space after the opening parenthesis and before the closing parenthesis:

\((?!\s)[^()]+(?<!\s)\)

(?!\s) and (?<!\s) mean "not followed by / not preceded by a space".

The part in the middle, [^()]+ requires one or more characters to be present between parentheses, disallowing () match.

Demo.

Upvotes: 1

Related Questions