开发者

JavaScript's regexp

开发者 https://www.devze.com 2023-02-15 03:49 出处:网络
Trying to parse the following text: This is one of the [name]John\'s[/name] first tutorials. or Please invite [name]Steven[/name开发者_如何学JAVA] to

Trying to parse the following text:

This is one of the [name]John's[/name] first tutorials.

or

Please invite [name]Steven[/name开发者_如何学JAVA] to the meeting.

What I need is to do a regexp in Javascript to get the name. Doing var str = body.match(/[name](.*?)[\/name]/g); works, but how do I get just the inside of it?


Try using the "exec" method of a regular expression to get the matching groups as an array:

var getName = function(str) {
  var m = /\[name\](.*?)\[\/name\]/.exec(str);
  return (m) ? m[1] : null;
}

var john = getName("This is one of [name]John's[/name] first tutorials.");
john // => "John's"
var steve = getName("Please invite [name]Steven[/name] to the meeting.");
steve // => "Steven"

This could be easily extended to find all occurrences of names by using a global RegExp:

var getAllNames = function(str) {
  var regex = /\[name\](.*?)\[\/name\]/g
    , names = []
    , match;
  while (match = regex.exec(str)) {
    names.push(match[1]);
  }
  return names;
}

var names = getAllNames("Hi [name]John[/name], and [name]Steve[/name]!");
names; // => ["John", "Steve"]


You want to access the matched groups. For an explanation, see here: How do you access the matched groups in a JavaScript regular expression?


You made a mistake in your regexp, you have to escape brackets: \[name\]. Just writing [name] in regexp means that there should be either 'n' or 'a' or 'm' or 'e'. And in your case you just want to tell that you look for something started with '[name]' as string

altogether:

/\[name\](.*?)\[\/name\]/g.exec('Please invite [name]Steven[/name] to the meeting.');
console.info( RegExp.$1 ) // "Steven"


You can use RegExp.$1, RegExp.$2, all the way to RegExp.$9 to access the part(s) inside the parenthesis. In this case, RegExp.$1 would contain the text in between the [name] and [/name].

0

精彩评论

暂无评论...
验证码 换一张
取 消