Copy parentheses with regex

My line: (as(dh(kshd)kj)ad)... ()()

How can parentheses be considered a regular expression? I would like to select a line that starts with the first open parenthesis and ends before...

Applying this to the above example, this means that I would like to get this line: (as(dh(kshd)kj)ad)

I tried to write it, but this does not work:

var str = "(as(dh(kshd)kj)ad)... ()()";
document.write(str.match(/(.*)/m));
+3
source share
6 answers

As I said in the comments, contrary to popular belief (do not believe everything that people say), matching parentheses is possible with a regular expression.

, . , , .

. . \([^()]*\) . . regex. , :

\(([^()]*|\(([^()]*|\([^()]*\))*\))*\)

: (as(dh(kshd)kj)ad)... ()()

DEMO HERE , .

. , , , [^()]* ([^()]*|\([^()]*\))* ( ). , .

+3

JavaScript regex. , , .

, (, PHP, Perl .NET), JavaScript .

+3

. , , , , .

function getFirstBracket(str){
  var pos = str.indexOf("("),
      bracket = 0;

  if(pos===-1) return false;

  for(var x=pos; x<str.length; x++){
    var char = str.substr(x, 1);    
    bracket = bracket + (char=="(" ? 1 : (char==")" ? -1 : 0));
    if(bracket==0) return str.substr(pos, (x+1)-pos);
  }
  return false;
}

getFirstBracket("(as(dh(kshd)kj)ad)... ()(");
+3

, : , , .

var str = "(as(dh(kshd)kj)ad)... ()()",
    match = str.match(new RegExp('.*?(?:\\(|\\)).*?', 'g')),
    count = match ? match.length : 0;

, . . http://gskinner.com/RegExr/ - .

count . match , :

["(", "as(", "dh(", "kshd)", "kj)", "ad)", "... (", ")", "(", ")"]

:

var newStr = '', open = 0, close = 0;

for (var n = 0, m = match.length; n < m; n++) {
    if (match[n].indexOf('(') !== -1) {
        open++;
        newStr += match[n];
    } else {
        if (open > close) newStr += match[n];
        close++;
    }
    if (open === close) break;
}

... newStr (as (dh (kshd) kj) ad)

, , , , .

.

+3

No. Regular expressions express regular languages. Finite state machines (FAs) are machines that recognize a common language. FA is, as the name suggests, finite in memory. With finite memory, the FA cannot remember an arbitrary number of parentheses - a function that is necessary in order to do what you want.

I suggest you use algorithms using an enumerator to solve your problem.

+2
source

try jsfiddle

var str = "(as(dh(kshd)kj)ad)... ()()";
document.write(str.match(/\((.*?)\.\.\./m)[1] );
+1
source

All Articles