java.util.regex ^ problem

G

Glenn Meter

I'm trying to use the regex package to match strings at the beginning
of lines within files. However, it looks like ^ is only matching on
items at the start of the string, not at the start of a line.

This sets b to true, with m.start() returning 0 [the beginning of text]:

Pattern p = Pattern.compile("^foo");
Matcher m = p.matcher("foo\nmatch bar\n");
boolean b = m.find();

This leaves b as false:

Pattern p = Pattern.compile("^match");
Matcher m = p.matcher("foo\nmatch bar\n");
boolean b = m.find();

Since the top test succeeds, it looks like it's taking '^' as a
boundary marker instead of the "not this character" marker.
The fact that RegexTestHarness only checks one line at a time isn't
giving me great confidence that multi-line input was thoroughly tested.

Any clues would be greatly appreciated.

Thanks,
Glenn
 
C

Chris Smith

Glenn said:
I'm trying to use the regex package to match strings at the beginning
of lines within files. However, it looks like ^ is only matching on
items at the start of the string, not at the start of a line.

From the API documentation for java.util.Pattern:

By default, the regular expressions ^ and $ ignore line terminators
and only match at the beginning and the end, respectively, of the
entire input sequence. If MULTILINE mode is activated then these
expressions match just after or just before, respectively, a line
terminator or the end of the input sequence with the exception that
the expression ^ never matches at the end of input, even if the last
character is a newline.

So try:

Pattern p = Pattern.compile("^match", Pattern.MULTILINE);
Matcher m = p.matcher("foo\nmatch bar\n");
boolean b = m.find();

I haven't tried it, but I suspect it will work.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top