用以asterix文字结尾的单词的Java正则表达式模式匹配

时间:2012-11-08 21:15:50

标签: java regex

我正在尝试使用java制作一个简单的正则表达式模式。我需要识别任何以尾随星号和句子结尾的大写单词。从以下示例:

Test ABC*  array
我需要识别“ABC *”或者确切地说,任何带有上框的单词以星号结尾。我尝试了以下模式匹配我有限的正则表达式知识,但到目前为止还没有成功。
String text = "Test ABC*  array";
Matcher m = Pattern.compile("\b[A-Z]+[*]?\b").matcher(text);
任何指针都将受到赞赏。

由于

4 个答案:

答案 0 :(得分:9)

问题是你在明星之后没有word boundary。所以试试这个

Matcher m = Pattern.compile("\\b[A-Z]+\\*\\B").matcher(text);

\B不是单词边界,因此这正是您在*和空格之间得到的结果。

here on Regexr

答案 1 :(得分:2)

假设您的字符串可以包含多个AAA *部分:

String text = "Test ABC*  array";
Matcher m = Pattern.compile("([A-Z]+\\*)").matcher(text);
while (m.find()) {
    System.out.println(m.group());
}

答案 2 :(得分:1)

我会保持简单:

if(text.contains("*")) {
  int index = text.lastIndexOf("*");
  String ident= text.substring(0,index-1);
}

答案 3 :(得分:0)

您必须使用反斜杠转义文字星号。它最终成为Java中的双反斜杠。

"[A-Z]+\\*"