Tim VN
Tim VN

Reputation: 1193

Regex for all capital letters between last 2 parentheses in string

I'm trying to get all capital letters between the last 2 parentheses in a string. So far I've tried this:

/\(([A-Z])([^)]*)\)[^(]*$/g

On for example: I don't want (These Words), I want (These Two)

but it gives me:

Group 1. T

Group 2. hese Two

Can someone help me?

Thanks in advance!

Upvotes: 1

Views: 1443

Answers (3)

mohessaid
mohessaid

Reputation: 390

You can get all the capital letters between the last string wrapped between parentheses in JavaScript as follow:

/(?!.*\()(?=.*\))([A-Z])/g

Where the first part (?!.*\(.*\)) is a negative lookahead which ignores all the opening parentheses and stops immediately after the last one. Then we perform a positive lookahead which matches everything until it encounters closing parentheses. Then we match the capital letters.

Upvotes: 0

Valdi_Bo
Valdi_Bo

Reputation: 31011

I think, the shortest and simplest solution is:

  • (?!.*\() - Negative lookahead - nowhere later can occur any opening parenthesis (after any number of other chars),
  • (?=.*\)) - Positive lookahead - somewhere later there must occur the closing parenthesis (after any number of other chars),
  • [A-Z] - Catch a capital letter, not as a capturing group, but as a "normal" match,
  • g - With global option.

To sum up:

/(?!.*\()(?=.*\))[A-Z]/g

Upvotes: 3

ctwheels
ctwheels

Reputation: 22837

Code

var s = "I don't want (These Words), I want (These Two)"
var r = /.*\(([^)]*)\)/
var m = r.exec(s)

console.log(m[1].match(/[A-Z]/g))


Explanation

First Regex

The first regex .*\(([^)]*)\).* extracts the contents of the last parentheses.

  • .* Match any character any number of times
  • \( Match a left parenthesis literally
  • ([^)]*) Capture any character except the right parenthesis any number of times into capture group 1
  • \) Match a right parenthesis literally
  • .* Match any character any number of times

Second Regex

The second regex [A-Z] matches uppercase letters

Upvotes: 0

Related Questions