简体   繁体   中英

Java regular expression match

I need to match when a string begins with number, then a dot follows, then one space and 1 or more upper case characters. The match must occur at the beginning of the string. I have the following string.

1. PTYU fmmflksfkslfsm

The regular expression that I tried with is:

^\d+[.]\s{1}[A-Z]+

And it does not match. What would a working regular expression be for this problem?

(Sorry for my earlier error. Brain now firmly engaged. Er, probably.)

This works:

String rex = "^\\d+\\.\\s\\p{Lu}+.*";

System.out.println("1. PTYU fmmflksfkslfsm".matches(rex));
// true

System.out.println(". PTYU fmmflksfkslfsm".matches(rex));
// false, missing leading digit

System.out.println("1.PTYU fmmflksfkslfsm".matches(rex));
// false, missing space after .

System.out.println("1. xPTYU fmmflksfkslfsm".matches(rex));
// false, lower case letter before the upper case letters

Breaking it down:

  • ^ = Start of string
  • \\d+ = One or more digits (the \\ is escaped because it's in a string, hence \\\\ )
  • \\. = A literal . (or your original [.] is fine) (again, escaped in the string)
  • \\s = One whitespace char (no need for the {1} after it) (I'll stop mentioning the escapes now)
  • \\p{Lu}+ = One or more upper case letters (using the proper Unicode escape — thank you, tchrist, for pointing this out in your comment below . In English terms, the equivalent would be [AZ]+ )
  • .* = Anything else

See the documentation here for details.

You only need the .* at the end if you're using a method like String#match (above) that will try to match the entire string.

It depends which method are you using. I think it will work if you use Matcher.find(). It will not work if you are using Matcher.matches() because match works on whole line. If you are using matches() fix your pattern as following:

^\d+\.\s{1}[A-Z]+.*

(pay attention on trailing .* )

And I'd also use \\. instead of [.] . It is more readable.

"^[0-9]+\\. [A-Z]+ .+"

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