Aisatora
Aisatora

Reputation: 352

getting values from a string using regular expression

Could anyone help me with this regular expression issue?

expr = /\(\(([^)]+)\)\)/;

input = ((111111111111))

the one I would need to be working is = ((111111111111),(222222222),(333333333333333))

That expression works fine to get 111111 from (input) , but not when there are also the groups 2222... and 3333.... the input might be variable by variable I mean could be ((111111111111)) or the one above or different (always following the same parenthesis pattern though)

Is there any reg expression to extract the values for both cases to an array?

The result I would like to come to is:

[0] = "111111"

[1] = "222222"

[2] = "333333"

Thanks

Upvotes: 1

Views: 114

Answers (3)

revo
revo

Reputation: 48711

If you are trying to validate format while extracting desired parts you could use sticky y flag. This flag starts match from beginning and next match from where previous match ends. This approach needs one input string at a time.

Regex:

/^\(\(([^)]+)\)|(?!^)(?:,\(([^)]+)\)|\)$)/yg

Breakdown:

  • ^\(\( Match beginning of input and immedietly ((
  • ( Start of capturing group #1
    • [^)]+ Match anything but )
  • )\) End of CG #1, match ) immediately
  • | Or
  • (?!^) Next patterns shouldn't start at beginning
  • (?: Start of non-capturing group
    • ,\(([^)]+)\) Match a separetd group (capture value in CG #2, same pattern as above)
    • | Or
    • \)$ Match ) and end of input
  • ) End of group

JS code:

var str = '((111111111111),(222222222),(333333333333333))';

console.log(
  str.replace(/^\(\(([^)]+)\)|(?!^)(?:,\(([^)]+)\)|\)$)/yg, '$1$2\n')
     .split(/\n/).filter(Boolean)
);

Upvotes: 3

Máté Safranka
Máté Safranka

Reputation: 4116

If the level of nesting is fixed, you can just leave out the outer () from the pattern, and add the left parentheses to the [^)] group:

var expr = /\(([^()]+)\)/g;
var input = '((111111111111),(222222222),(333333333333333))';

var match = null;
while(match = expr.exec(input)) {
    console.log(match[1]);
}

Upvotes: 2

Muhammad Usman
Muhammad Usman

Reputation: 10148

You can replace brackes with , split it with , and then use substring to get the required number of string characters out of it.

input.replace(/\(/g, '').replace(/\)/g, '')

This will replace all the ( and ) and return a string like

111111111111,222222222,333333333333333

Now splitting this string with , will result into an array to what you want

var input = "((111111111111),(222222222),(333333333333333))";

var numbers = input.replace(/\(/g, '').replace(/\)/g, '')

numbers.split(",").map(o=> console.log(o.substring(0,6)))

Upvotes: 2

Related Questions