Regex Groups  
Author Message
Andreas Knollmann





PostPosted: 2005-3-10 5:16:00 Top

java-programmer, Regex Groups Hi,

I have a question concerning the behavior of regular expressions in Java. I
have a text: "text-123-234-535-235"

I use a regular expression to get the text: "text(-[0-9]*)*".

The problem is that I don't how many number blocks there will be. It can one
or twenty. Java only delivers me the last matched block as group. How can I
get all?

I can't use String.split because the regex is configued in a config file and
the regex can change as can the text. So the Java code needs to be flexible
what to do.

Is there any way to do this?

Thanks,
Andreas


 
Thomas Schodt





PostPosted: 2005-3-10 6:17:00 Top

java-programmer >> Regex Groups Andreas Knollmann wrote:
> Hi,
>
> I have a question concerning the behavior of regular expressions in Java. I
> have a text: "text-123-234-535-235"
>
> I use a regular expression to get the text: "text(-[0-9]*)*".
>
> The problem is that I don't how many number blocks there will be. It can one
> or twenty. Java only delivers me the last matched block as group. How can I
> get all?
>
> I can't use String.split because the regex is configued in a config file and
> the regex can change as can the text. So the Java code needs to be flexible
> what to do.
>
> Is there any way to do this?


Specify your way out of this one.


Require that the pattern specify each group explicitly.

"text(-[0-9]*)?(-[0-9]*)?(-[0-9]*)?(-[0-9]*)?(-[0-9]*)?(-[0-9]*)?"



Or, require that the pattern is to have a maximum of
one "repeated capturing group"
and have your application parse *the regex*. So from

"text(-[0-9]*)*"

your application generates

"text(-[0-9]*)?(-[0-9]*)?(-[0-9]*)?(-[0-9]*)?(-[0-9]*)?(-[0-9]*)?"

to do the actual matching.


You have to decide how many optional capturing groups you will generate
for a "repeated capturing group" - or make it depend on the length of
the text to be matched - or something.