1

I have following string:

@[A:B:C].[X:Y:Z].[P:Q:R] 1.C.3.s @[1:2:3].[2:0:0].[5dsh:cxcv:wew]

I want to extract sub-strings from these that are in following format:

@[anything here].[anything here].[anything here]

In above case the output sub-strings should be:

@[A:B:C].[X:Y:Z].[P:Q:R]
@[1:2:3].[2:0:0].[5dsh:cxcv:wew]

I have this regular expression that matches these sub-strings:

(@\w+|@(?:\[[^\]]+\]\.?)+)

To test this regular expression I am replacing these sub-strings with $ in this fiddle: http://jsfiddle.net/vfe50z0o/

There is no problem with the regular expression as it is working in this Regex101 demo: https://regex101.com/r/aH9nK5/1

But on JSFiddle it's not working.

This is JavaScript code:

function myFunction() {
    var re = /(@\w+|@(?:\[[^\]]+\]\.?)+)/; 
    var str = 'wewe@[s].[s].[s]xvcv';
    var subst = '$';
    var result = str.replace(re, subst);
    alert(result);
}
2
  • 1
    The fiddle doesn't work because you've put your function in a "load" handler, and therefore it isn't global so the event handler fails. Change the fiddle setting to "nowrap - in body" and your fiddle works fine. Commented Jun 30, 2015 at 14:15
  • @Pointy Thanks that solved the problem. Add it as answer I will mark. Commented Jun 30, 2015 at 14:20

2 Answers 2

0

If you are dealing with such format strings the following regex can does the job :

(@?\[[^[]*\]\.?){3}

Demo

If the number of brackets can be more or less than 3 you can use + :

(@?\[[^[]*\]\.?)+
Sign up to request clarification or add additional context in comments.

Comments

0

You can use this code to get your matches:

var re = /(@\w*(?:\[[^\]]+\]\.?)+)/g; 
var str = '@[A:B:C].[X:Y:Z].[P:Q:R] 1.C.3.s @[1:2:3].[2:0:0].[5dsh:cxcv:wew]';
var m;

while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex)
        re.lastIndex++;
    console.log(m[1]);
}

Output:

@[A:B:C].[X:Y:Z].[P:Q:R]
@[1:2:3].[2:0:0].[5dsh:cxcv:wew]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.