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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13297934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:11:20  来源:igfitidea点击:

Java regex pattern matching for word ending with asterix literal

javaregex

提问by Shamik

I'm trying to make a simple regex pattern work using java. I need to recognize any uppercase word ending with trailing asterisk with a sentence. From the following example :

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

Test ABC*  array
我需要识别“ABC*”,或者更准确地说,任何以星号结尾的大写字母。我用我有限的正则表达式知识尝试了以下模式匹配,但到目前为止还没有成功。
String text = "Test ABC*  array";
Matcher m = Pattern.compile("\b[A-Z]+[*]?\b").matcher(text);
String text = "Test ABC*  array";
Matcher m = Pattern.compile("\b[A-Z]+[*]?\b").matcher(text);
任何指针将不胜感激。

Thanks

谢谢

回答by stema

the problem is that you don't have a word boundaryat the end after the star. So try this

问题是在星号之后的末尾没有单词边界。所以试试这个

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

\Bis not a word boundary, so this is exactly what you get between the *and a whitespace.

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

See it here on Regexr

在 Regexr 上看到它

回答by flawyte

Assuming your string can contain multiple AAA* parts :

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

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

回答by David Sonnenfeld

I would keep it simple:

我会保持简单:

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

回答by jimbo

You have to escape the literal asterisk with a backslash. It ends up being a double-backslash in Java.

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

"[A-Z]+\*"