Alexey Kulikov
Alexey Kulikov

Reputation: 1147

extract values using regexp

Hello where is some text patterns like:

some text Here +0.25(2)
some text Here 0.25(2.3)
some text Here 0.00(2.3)
some text Here -1.5(1.5)
...
some text Here param_1(param_2)

I need to extract two values param_1 and param_2. How to solve it using regexpressions? (needed Javascript)

param_1 is number contais +, - or nothing perfix. param_2 is number

Upvotes: 1

Views: 44

Answers (2)

vks
vks

Reputation: 67968

([+-]?\d+(?:\.\d+)?)\((\d+(?:\.\d+)?)(?=\))

Try this.See demo.Grab the captures.

https://regex101.com/r/vD5iH9/25

var re = /([+-]?\d+(?:\.\d+)?)\(\d+(?:\.\d+)?(?=\))/g;
var str = 'some text Here +0.25(2)\nsome text Here 0.25(2.3)\nsome text Here 0.00(2.3)\nsome text Here -1.5(1.5)\n...\nsome text Here param_1(param_2)';
var m;

while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}

EDIT:

(.*?)\s([+-]?\d+(?:\.\d+)?)\((\d+(?:\.\d+)?)(?=\))

use this to capture all three components.See demo.

https://regex101.com/r/vD5iH9/28

Upvotes: 1

user3310334
user3310334

Reputation:

I assume that you would like an array of param_1s, and then an array of param_2s.

You can accomplish this with two simple regex's:

(to capture param_1s):

/[+-\d.]+(?=\([\d.]+\)$)/gm

param_1 demo

and param_2's are even simpler:

/[\d.]+(?=\)$)/gm

Try the full jsFiddle demo.

var param1 = str.match(/[+-\d.]+(?=\([\d.]+\)$)/gm);
var param2 = str.match(/[\d.]+(?=\)$)/gm);

param1 is now an array containing param_1s, and param2 for param_2s.

Upvotes: 1

Related Questions