繁体   English   中英

Java正则表达式字符串匹配

[英]Java Regular Expression string match

我需要帮助。 我正在写一个方法,如果1954在字符串images/deal/129277/1954-bonus.jpg ,它将返回true。 我可以使用string.contains,但它并不总是准确的。 相反,如果1954年在正确的位置,我希望它返回true。 在sourceKey下面是images/deal/129277/1954-bonus.jpgimages/deal/129277/1954-bonus.jpg1954

下面的代码不起作用。

private boolean keyMatches(String sourceKey, String oldImageId){
    Pattern pattern = Pattern.compile("(.*?)/(\\d+)/(\\d+)-(.*)");
    Matcher matcher = pattern.matcher(sourceKey);
    return oldImageId.equals(matcher.group(3));
}

好像您想要这样的东西,

String s = "images/deal/129277/1954-bonus.jpg";
String oldImageId = "1954";
Matcher m = Pattern.compile("(.*?)/(\\d+)/(\\d+)-(.*)").matcher(s);
if(m.find())
{
System.out.println(oldImageId.matches(m.group(3)));
}

输出:

true

尝试这样的事情:

public static void main(String[] args) {
    String s = "images/deal/129277/1954-bonus.jpg";
    String s1 = "images/deal/1954/1911254-bonus.jpg";
    System.out.println(s.matches(".*/1954\\-.*"));
    System.out.println(s1.matches(".*/1954\\-.*"));
}

O / P:

true
false

我可以在您的代码中看到至少一个错误。 除非您之前调用find()match()方法并且这些方法返回true否则Matcher不会返回任何组。

因此,您的代码应修改如下:

Matcher matcher = pattern.matcher(sourceKey);
return matcher.find() ? oldImageId.equals(matcher.group(3)) : null;

我留给您来验证您的正则表达式确实正确。

使用regex lookahead和String#matches()您的函数可能像

private boolean keyMatches(String sourceKey, String oldImageId){
    return sourceKey.matches(".*/(?!.*/)"+oldImageId+"-.*");
}

我在URL的各个部分进行了1954的以下测试,以欺骗正则表达式。

System.out.println(keyMatches("images/deal/129277/1954-bonus.jpg", "1954"));
System.out.println(keyMatches("images/deal/1954-pics/129277-bonus.jpg", "1954"));
System.out.println(keyMatches("123-1954/1954-00/1954/129277-bonus.jpg", "1954"));
System.out.println(keyMatches("images/deal/129277/129277-1954-bonus.jpg", "1954"));

输出:

true
false
false
false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM