Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

RegEx in Java: how to deal with newline

I am currently trying to learn how to use regular expressions so please bear with my simple question. For example, say I have an input file containing a bunch of links separated by a newline:

www.foo.com/Archives/monkeys.htm
Description of Monkey's website.

www.foo.com/Archives/pigs.txt
Description of Pig's website.

www.foo.com/Archives/kitty.txt
Description of Kitty's website.

www.foo.com/Archives/apple.htm
Description of Apple's website.

If I wanted to get one website along with its description, this regex seems to work on a testing tool: .*www.*\s.*Pig.*

However, when I try running it within my code it doesn't seem to work. Is this expression correct? I tried replacing "s" with " " and it doesn't seem to work still.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The lines are probably separated by in your file. Both (carriage return) and (linefeed) are considered line-separator characters in Java regexes, and the . metacharacter won't match either of them. s will match those characters, so it consumes the , but that leaves .* to match the , which fails. Your tester probably used just to separate the lines, which was consumed by s.

If I'm right, changing the s to s+ or [ ]+ should get it to work. That's probably all you need to do in this case, but sometimes you have to match exactly one line separator, or at least keep track of how many you're matching. In that case you need a regex that matches exactly one of any of the three most common line separator types: (Windows/DOS), (Unix/Linus/OSX) and (older Macs). Either of these will do:


|[
]


|
|


Update: As of Java 8 we have another option, R. It matches any line separator, including not just , but several others as defined by the Unicode standard. It's equivalent to this:


|[
x0Bx0C
u0085u2028u2029]

Here's how you might use it:

(?im)^.*www.*R.*Pig.*$

The i option makes it case-insensitive, and the m puts it in multiline mode, allowing ^ and $ to match at line boundaries.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...