Java正则表达式匹配 [英] Java regular expression match

查看:192
本文介绍了Java正则表达式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当字符串以数字开头,然后是一个点,然后是一个空格和一个或多个大写字符时,我需要匹配。匹配必须出现在字符串的开头。我有以下字符串。

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?

推荐答案

(对不起我之前的错误。大脑现在坚定地参与其中呃,可能。)

这个有效:

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

分解:


  • ^ =字符串开头

  • \d + =一个或多个数字 \ 被转义,因为它在字符串中,因此 \\

  • \。 =文字(或你原来的 [。] 很好)(再次,在字符串中转义)

  • \s =一个空白字符(不需要 {1} 之后)(我现在不再提及逃脱)

  • \p {Lu} + =一个或多个大写字母(使用正确的Unicode转义 — 谢谢你,tchrist,在下面的评论中指出这一点。在英语术语中,相当于将 [AZ] +

  • 。* =其他任何

  • ^ = 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 [A-Z]+)
  • .* = Anything else

参见此处的文档了解详情。

如果你使用像 String #matc 这样的方法,你最后只需要。* (以上)将尝试匹配整个字符串。

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.

这篇关于Java正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆