1

i want to match string in javascript, but take only part from matched string.

E.g i have string 'my test string' and use match function to get only 'test':

var text = 'my test string';
var matched = text.match(/(?=my).+(?=string)/g);

iam tried to get it in this way but it will return 'my test'. How can i do this to get only 'test' with regex?

Filip
  • 105
  • 11
  • Use capturing group #1 as `/my (.+?)(?= string)/` – anubhava Oct 05 '15 at 19:12
  • Relevant: [what is the difference between ?:, ?! and ?= in regex?](http://stackoverflow.com/questions/10804732/what-is-the-difference-between-and-in-regex) and [Javascript positive lookbehind alternative](http://stackoverflow.com/questions/27265515/javascript-positive-lookbehind-alternative). Your first group is a lookahead, not a lookbehind. JS doesn't support lookbehind. – apsillers Oct 05 '15 at 19:13

2 Answers2

0

You can use a capture group:

var match = text.match(/my (.*) string/g);
# match[0] will be the whole string, match[1] the capture group
match[1];

this will still match the whole string, but you can get the contents with match[1].

Some other regex engines have a feature called "lookbehind", but this is unsupported in JavaScript, so I recommend the method with the capture group.

pixunil
  • 641
  • 1
  • 5
  • 19
  • `match` will be: `["my test string"]`. The `string.match` function returns only $0 group (as many times as it matched) – Ron C Oct 05 '15 at 19:45
0

You need to change your regex to /my (.+) string/g and create RegExp object from it:

var regex = new RegExp(/my (.+) string/g);

Then use regex.exec(string) to get the capturing groups:

var matches = regex.exec(text);

matches will be an array with the value: ["my test string", "test"].

matches contains 2 groups: $0 and $1. $0 is the whole match, and $1 is the first capturing group. $1 it's what inside the parentheses: .+.

You need $1, so you can get it by writing matches[1]:

//This will return the string you want
var matched = matches[1];
Ron C
  • 1,176
  • 9
  • 12