获取字母的最后一个索引,后跟数字

Get the last index of a letter followed by numeric

我正在尝试解析 URL,我想测试几个字符的最后一个索引,后跟一个数值。

例子 used-cell-phone-albany-m3359_l12201

我正在尝试确定最后一个“-m”是否后跟一个数值。

所以像这样,"used-cell-phone-albany-m3359_l12201".contains("m" followed by numeric)

我假设它需要用正则表达式来完成,但我不确定。

在 Java 中,如有必要,将 URL 转换为字符串,然后 运行

URLString.match("^.*m[0-9]+$").

只有当 returns 为真时,URL 才以 "m" 后跟一个数字结尾。可以使用更精确的结束模式对其进行改进。此正则表达式在字符串末尾测试模式的原因是因为正则表达式中的 $ 匹配字符串的末尾; "[0-9]+" 匹配一个或多个数字的序列; “^”匹配字符串的开头;和“.*”匹配零个或多个任意但可打印的字符,包括白色 space、字母、数字和标点符号。

要确定最后一个 "m" 后面是否跟一个数字然后使用

URLString.match("^.+?m[0-9].*$")

这里是“.+?”贪婪地匹配所有字符直到最后 "m".

您可以使用像 [a-z]\d 这样的模式来搜索出现在 a-z 之间字符旁边的任何数字,如果您愿意,您可以指定组内的其他字符...

Pattern pattern = Pattern.compile("[a-z]\d", Pattern.CASE_INSENSITIVE);        
Matcher matcher = pattern.matcher("used-cell-phone-albany-m3359_l12201");

while (matcher.find()) {

    int startIndex = matcher.start();
    int endIndex = matcher.end();

    String match = matcher.group();

    System.out.println(startIndex + "-" + endIndex + " = " + match);

}

问题是,您的测试 String 实际上包含两个匹配项 m3l1

上面的例子会显示

23-25 = m3
29-31 = l1

已根据反馈更新

如果能保证marker(即-m),那就简单多了...

Pattern pattern = Pattern.compile("-m\d", Pattern.CASE_INSENSITIVE);       
Matcher matcher = pattern.matcher("used-cell-phone-albany-m3359_l12201");

if (matcher.find()) {

    int startIndex = matcher.start();
    int endIndex = matcher.end();

    String match = matcher.group();

    System.out.println(startIndex + "-" + endIndex + " = " + match);

}