Regex: string match against mutiple patterns

T

thorsten

Hi,

I have a textfile which read line by line. Each line should be
checked, if there is a match against five different patterns.

1) How must i write the pattern for five matches

2) How can i get the text after the match up to the next space

Perhaps there is somebody who has done this before.

Thanks for any ideas

Thorsten
(Regex Newbie)
 
H

HK

thorsten said:
Hi,

I have a textfile which read line by line. Each line should be
checked, if there is a match against five different patterns.

1) How must i write the pattern for five matches

import java.util.regex.*;
Pattern p = Pattern.compile("("+re1+")"
+"|"...+"|"
"("+re5+")")
Matcher m = p.matcher(line_of_text);
if( m.matches() ) {
// do what has to be done
2) How can i get the text after the match up to the next space

int end = m.end();
Pattern space = Pattern.compile("[^ ]*");
Matcher ms = space.matcher(line_of_text.substring(end));
String textUptoSpace = ms.group(0);
}

The problem with this solution is, that you don't know which pattern
actually matched. To know this, you would need an if/elseif/else
cascade. Of course you also need the loop over the input lines.
To read a small config file occasionally, there is nothing wrong with
this approach.

For high speed/high volume text processing, you may want to try

http://www.ebi.ac.uk/Rebholz-srv/whatizit/monq-doc/monq/jfa/package-summary.html#package_description

You basically specify regex/action pairs such that the action is
called whenever the associated regex is spotted in the input. Looping
through an input stream is taken care of by the system. You
concentrate on what has to happen when a specific regex is seen.

Harald.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top