获取字符串末尾没有小写字母的子字符串

Get substring at end of string that has no lowercase letters

我有这样的字符串:

[POS Purchase]
POS Signature Purchase International  SKYPE COMMUNICATIO, LUXEMBOURG, LUX

或:

ATM Cash Withdrawal. Surcharge: -3.0  BNEAIR INT DP LSL4 2, BNE AIRPORT, AUS

而且我想获取除小写字母以外的任何字符的字符串结尾。对于上面的两个例子,答案应该是:

SKYPE COMMUNICATIO, LUXEMBOURG, LUX

BNEAIR INT DP LSL4 2, BNE AIRPORT, AUS

如何使用正则表达式实现此目的?

根据您的需要,您正在寻找以下正则表达式:

[^a-z]+$

否定字符 class [^a-z]+ 将匹配 none 小写字符的任意组合,锚点 $ 将使正则表达式引擎匹配字符串的末尾.

但是请注意,这将在你的第二个 example.And 中匹配 -3.0 如果你想使用它,你可以将 [A-Z] 放在你的正则表达式的开头:

[A-Z][^a-z]*$

Debuggex Demo


您可以从这里开始了解有关正则表达式的更多信息http://www.regular-expressions.info/

您可以使用这个正则表达式:

[A-Z][A-Z\d, ]*$

MULTILINE 模式下匹配您的数据。

这将匹配以大写字母开头且后跟大写字母或数字或 space 或逗号的文本。

在Java中使用:

Pattern regex = Pattern.compile("(?m)[A-Z][A-Z\d, ]*$");

RegEx Demo

您可以使用以下自包含的example/pattern来匹配以大写单词字符开头且不包含任何小写字符的最后一串字符:

String[] input = {
    "[POS Purchase]" + 
    System.getProperty("line.separator") + 
    "POS Signature Purchase International  SKYPE COMMUNICATIO, LUXEMBOURG, LUX",

    "ATM Cash Withdrawal. Surcharge: -3.0  BNEAIR INT DP LSL4 2, BNE AIRPORT, AUS"
};
//                            | starts with uppercase letter
//                            |      | uppercase letters or no letters
//                            |      |           | 0 or more times
//                            |      |           | | end of input
//                            |      |           | | 
Pattern p = Pattern.compile("\p{Lu}[\p{Lu}\P{L}]*$");
for (String s: input) {
    Matcher m = p.matcher(s);
    if (m.find()) {
        System.out.println(m.group());
    }
}

输出

SKYPE COMMUNICATIO, LUXEMBOURG, LUX
BNEAIR INT DP LSL4 2, BNE AIRPORT, AUS