gpt4 book ai didi

java - 为什么这个正则表达式与 Java 中的这种颜色不匹配?

转载 作者:行者123 更新时间:2023-12-01 22:12:22 26 4
gpt4 key购买 nike

常见的十六进制颜色代码正则表达式与颜色 #79bff7 匹配得很好,但在我的 Java 程序中失败了。

我使用的颜色 validator 只是 HexValidator 的副本.

public class HexValidator{

private Pattern pattern;
private Matcher matcher;

private static final String HEX_PATTERN = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";

public HexValidator(){
pattern = Pattern.compile(HEX_PATTERN);
}

/**
* Validate hex with regular expression
* @param hex hex for validation
* @return true valid hex, false invalid hex
*/
public boolean validate(final String hex){

matcher = pattern.matcher(hex);
return matcher.matches();

}
}

我希望看到特定的颜色匹配,就像在线正则表达式匹配器(如regex101)上的那样。 .

最佳答案

当不匹配时打印一条消息。包含引号,以便您可以查看是否有空格。

public boolean validate(final String hex){
matcher = pattern.matcher(hex);
boolean matches = matcher.matches();
if (!matches)
System.out.println ("not a hex color string: \"" + hex + "\" length: " + hex.length());
return matches;
}

关于java - 为什么这个正则表达式与 Java 中的这种颜色不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58649642/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com