C
C
couatl2011-12-02 17:23:47
Regular Expressions
couatl, 2011-12-02 17:23:47

Patterns (grouping) in regular expressions and keeping more than just the first occurrence

In regular expressions, there is such a thing as grouping, which helps to pull out several parts at once using a regular expression. It is denoted with parentheses.
The matter is that only the first occurrence is saved. Here's an example: Here's the result: Is it possible somehow , using grouping , to rip out not only the first occurrence, but all of them? That is the desired result:
str = Mama mila ramu
regex = (?:([A-Za-z]+)\s?)+


0: (Mama mila ramu) // тут вопросов нет, выражение как раз выдирает всю строку
1: (ramu) // вот оно первое вхождение



0: (Mama mila ramu)
1: (Mama)
2: (mila)
3: (ramu)


Naturally, all this is not done for this example.
My example where I encountered this problem:
There is a COP-grammar and its rules I want to establish with one regular expression whether the rule is correct and tear everything out of the rule. Wrote the following regular expression: \b([AZ])->(?:([A-Za-z]+)\|?)+ But of course, it gets only the first occurrence from the right side using grouping. Result for S->a|AS: but you need
S->a|AS
A->AB
B->b

0: (S->a|AS)
1: (S)
2: (AS)

0: (S->a|AS)
1: (S)
2: (a)
3: (AS)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wott, 2011-12-02
@Wott

it is possible, just for this purpose usually a separate call/syntax
what language?

W
Weageoo, 2011-12-02
@Weageoo

In a good way, you need to use k.-l. compiler generator by describing the grammar in BNF or EBNF. Regular expressions will not provide the necessary flexibility.
More or less, if the language is simple, regular expressions can highlight lexemes (split the expression). It would be necessary to check the correctness with a parser.
Specifically for your case something like (Python):
>>> import re
>>> re.findall("^(([AZ])->([A-Za-z]+)\|([AZ] +))", "S->a|AS")
[('S->a|AS', 'S', 'a', 'AS')]
Or re.match(...).group( n) use ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question