javascript - Regex Match value in Typescript - Stack Overflow

I am trying to extract the value of certain pattern from the text.Sample text: Test: []subtests: [a]I

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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744855261a4597365.html

相关推荐

  • javascript - Regex Match value in Typescript - Stack Overflow

    I am trying to extract the value of certain pattern from the text.Sample text: Test: []subtests: [a]I

    2天前
    60

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信