Andreas Köberle
Andreas Köberle

Reputation: 110922

Find pattern in every line with JavaScript

Lets say I have the following string

def name1
 toSomething

def name2 
  toSomethingElse

How could I find name1 and name2.

Using string.match(/(?:def) (.*)/) gives me:

name1
 toSomething

def name2 
  toSomethingElse

So how can I search the string line by line?

Upvotes: 1

Views: 106

Answers (3)

Oscar Mederos
Oscar Mederos

Reputation: 29843

You could try with:

/(?:def)\s+([^\s]+)/g

In the first group you will have what you need (name1, etc).

See here: http://regex101.com/r/rH0yH8

An example of how to run it:

var s = "def name1\ntoSomething\n\ndef name2 \ntoSomethingElse"
var re = /(?:def)\s+([^\s]+)/g

while (x = re.exec(s)) {
    alert(x[1])
}

Upvotes: 1

Mike Samuel
Mike Samuel

Reputation: 120516

/^def (.*)/gm

will do it. The g flag matches every instance, and the m flag causes the ^ to match at the beginning of a line instead of at the beginning of the input only.

With .exec, you can loop and get the results one at a time.

var myString = 'def foo\n  boo\n\ndef bar\n  far\n';
for (var re = /^def (.*)/gm, match; (match = re.exec(myString));) {
  alert(match[1]);
}

or you can use .match on the string to get all of the results in one array, but that doesn't give you the capturing groups.

var myString = 'def foo\n  boo\n\ndef bar\n  far\n';
var re = /^def (.*)/gm;
var matches = myString.match(re);

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Your regex should just give you the match on the first line, since . does not match newlines.

That said, try /(?:def)\s+(\S*)/

Upvotes: 0

Related Questions