最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex Match value in Typescript - Stack Overflow

programmeradmin3浏览0评论

I am trying to extract the value of certain pattern from the text.

Sample text:

Test: []
subtests: [a]

I want to extract the line subtests: [a] or precisely what's the data inside [] of subtests. When I try to match the regex, it's giving wrong value. Not sure what I am doing wrong here.

/

Can anyone help me out?

I am trying to extract the value of certain pattern from the text.

Sample text:

Test: []
subtests: [a]

I want to extract the line subtests: [a] or precisely what's the data inside [] of subtests. When I try to match the regex, it's giving wrong value. Not sure what I am doing wrong here.

https://jsfiddle/k8e9hu0e/2/

Can anyone help me out?

Share asked Mar 30, 2016 at 8:32 RaceBaseRaceBase 18.9k50 gold badges150 silver badges210 bronze badges 4
  • Use /g global modifier and loop through all matches. If you need the contents inside [...], you need a capture group. Check this fiddle. – Wiktor Stribiżew Commented Mar 30, 2016 at 8:34
  • @WiktorStribiżew, can you please modify the code and show the solution to munity? I am new to regex, it will be helpful for others like me – RaceBase Commented Mar 30, 2016 at 8:37
  • 1 Check jsfiddle/h8bf0ox5. Or if you need to only show the match value, use .exec(string)[0] - jsfiddle/u1paL0y2 – Wiktor Stribiżew Commented Mar 30, 2016 at 8:37
  • All you had to do is read the docs: If the match succeeds, the exec() method returns an array... The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured. – Wiktor Stribiżew Commented Mar 30, 2016 at 8:56
Add a ment  | 

2 Answers 2

Reset to default 1

Here is a Working Fiddle. So the only change was to remove the captures ie: changing (.*) to .*

Explaining your problem..

This regex ^subtests: (.*) has captures in it. And when you find the matches for this regex, it gives you a set of all the regex matches and then all the capture's. So the first set is subtests: [] and then the set of captures that is []. Hence your output was subtests: [],[] (note the ,).

Here is a live demo. Forked and modified from your source. https://jsfiddle/soonsuweb/aj38617b/

var data = `blur blur subtests: [] blur\nblur`;
var regex = /subtests: \[.*\]/;
var test = regex.exec(data);
alert("Op: " + test);
发布评论

评论列表(0)

  1. 暂无评论