简体   繁体   中英

Java Regex :: first word in each line of a String

Let's look at the following String:

String input = "A bla bla bla A blaa\r\n" +
               "B boo foo A B abo \r\n" + 
               "A yow B B yow";

And here is my regex:

String regex = "([AB]) (.*?)(?=$|[AB])";

I get with it each "A" or "B".

But what I look for is to get "A" or "B" only if it's the first word in each line of my String.

Thanks in advance.

You need to 2 things here:

  • Enable MULTILINE mode
  • Use ^ to match the AB only at the beginning.

This regex would work:

"(?m)^[AB]"

Pattern: ([AB]).*

Match:
1) A & A bla bla bla B blaa
2) B & B boo foo AB ab
3) A & A yow BB yow

Explain what you need. Look for results: http://fiddle.re/c1rwn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM