user3111525
user3111525

Reputation: 5203

Java Regex: replace with capturing group

I have a string like this:

123456-1/1234/189928/2323 (102457921)

I want to get 102457921. How can I achieve it with regex?

I have tried:

"123456-1/1234/189928/2323 (102457921)".replaceAll("(\\.*\()(\d+)(\))","$2");

But it does not work. Any hints?

Upvotes: 0

Views: 131

Answers (5)

user3578445
user3578445

Reputation:

You can try something like that:

var str = '123456-1/1234/189928/2323 (102457921)';
    console.log(str.replace(/[-\d\/ ]*\((\d+)\)/, "$1"));
    console.log((str.split('('))[1].slice(0, -1));
    console.log((str.split(/\(/))[1].replace(/(\d+)\)/, "$1"));
    console.log((str.split(/\(/))[1].substr(-str.length - 1, 9));
    console.log(str.substring(str.indexOf('(') + 1, str.indexOf(')')));

In other case you must be familiar with the specifics of the input data to generate a suitable regexp.

Upvotes: 0

Vassilis Blazos
Vassilis Blazos

Reputation: 1610

What about a "double" replaceAll regex simplified one

"123456-1/1234/189928/2323 (102457921)".replaceAll(".*\\(", "").replaceAll("\\).*", "");

Upvotes: 0

sshashank124
sshashank124

Reputation: 32189

You could do it as:

"123456-1/1234/189928/2323 (102457921)".replaceAll(".*?\(([^)]+)\)","$1");

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

Well, you can do this:

"123456-1/1234/189928/2323 (102457921)".replaceAll(".*\((.+)\)","$1");

Upvotes: 1

Keppil
Keppil

Reputation: 46209

How about

"123456-1/1234/189928/2323 (102457921)".replaceAll(".*?\\((.*?)\\).*", "$1");

Upvotes: 5

Related Questions