T
T
Timofey Mikhailov2017-10-09 08:11:32
JavaScript
Timofey Mikhailov, 2017-10-09 08:11:32

Can you help me with a regular expression?

var regul = /(AAA|BBB|CCC|DDD)\(.*?\)/g;
var str = "one two 12AAA(CCC(C1_1);A1_1)dfg "+
              "dfgdfgdfg,BBB(B1_1; B1_2) sfsgndf "+
              "dfgnhjdfglkjdfg DDD(D1_1)";
var ARR = str.match( regul );

for(var i = 0; i < ARR.length; i++) {
    console.log((i+1)+') '+ARR[i]);
}

Actually, what's the problem ...
In my case. the regular expression produces the following result:
1) AAA(CCC(C1_1)
2) BBB(B1_1; B1_2)
3) DDD(D1_1)
And I need the script to produce the following:
1) AAA(CCC(C1_1);A1_1)
2) CCC(C1_1)
3) BBB(B1_1; B1_2)
4) DDD(D1_1) Tell me
, is it possible to achieve the desired result using regular expressions? Or will I have to take additional steps?
Essence: I need to write a regular function in such a way that it understands that: CCC (), is inside AAA ()
For help, I will be grateful!
Link: https://jsfiddle.net/kh9h71kL/

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DTX, 2017-10-09
@DirecTwiX

Obviously, we need recursive regular expressions.
https://regex101.com/r/SBqnii/7
You can play around with groups. Probably, I will have to skip the regular expression by the result again, but I think it's easier and maybe even faster than using a state machine. And I would look at an example of such an automaton :)
Performance comparison with a finite automaton:
https://jsperf.com/regex-vs-fsa/1

R
Roman Dubinin, 2017-10-09
@romash

The answer is not correct, but I wrote it for too long, so I feel sorry for deleting it :D
This is how you can get
1) AAA(CCC(C1_1);A1_1);
2) BBB(B1_1; B1_2);
3) DDD(D1_1).
I'm not sure, but as far as I know, since it CCC(C1_1)is already in the found (inside AAA(CCC(C1_1);A1_1)), you won't find it the second time, for this you have to repeat the parsing for group 2 of each inclusion.
Also in the example, you can see that the triple nesting under this rule is no longer suitable. You can extend the regular expression to catch any finite number of nestings, but personally I would not recommend using them for such tasks. I note that I'm not very good at regular seasons, so maybe my advice is incorrect, in which case I apologize.
UPD: Changed the example. The previous regular expression looked for AAA(bar; BBB(); foo) but got confused with AAA(BBB(); foo; DDD(); bar).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question