4

I would like to come up with a regex for the following:

<action>::=Action(<entity><entity><Asset>)

I would like to have tokens such as :

Action(
<entity>
<entity>
<Asset>
)

entity and asset have <> around them and Action is followed by "(". However, ")" is an independent token. I am using the following:

([a-zA-Z]+\\()|((<.*?>)|([a-zA-Z]*))|(\\))?

but it fails to show the ")" as token? What am I doing wrong?

3 Answers 3

1

Try this regex :

([a-zA-Z]*\\()|(<[a-zA-Z]*>)|(\\))
Sign up to request clarification or add additional context in comments.

Comments

0

This should work for your example:

(\\w+\\()(<\\w+?>)(<\\w+?>)(<\\w+?>)(\\))

fiddle.re online demo

Comments

0

Something is actually wrong with your regular expression, or at least it makes the expression behave in an unexpected manner (to me).

The expression can be decomposed as such:

([a-zA-Z]+\\()| (?# matches alphabetical characters and an opening round-bracket)
    ((<.*?>)| (?# non-greedily matches anything between brackets)
    ([a-zA-Z]*))| (?# 3rd pattern: may match an empty string)
(\\))? (?# 4th pattern: optionally matches a closing round bracket)

Since the | operator is never greedy, the third pattern is triggered (matching an empty string) before the 4th pattern you actually want is.

Proof of this is that the tokens you actually get with your regular expression are:

''
''
''
'Action('
'<entity>'
'<entity>'
'<Asset>'
''
''

Therefore what you want is probably something like this:

([a-zA-Z]+\\()| (?# matches alphabetical characters and an opening round-bracket)
(<.*?>)| (?# non-greedily matches anything between brackets)
(\\)) (?# matches a closing round bracket)

Please note I removed the ? operator from the 4th pattern which was weirdly put outside the brackets and which also captured empty string.

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.