[英]java.util.regex.PatternSyntaxException: Illegal repetition near index 12
I am new to regEx.我是正则表达式的新手。 I need to validate email using java.我需要使用 java 验证 email。 I have created regEx for email validation by hardcoding the domain name.我通过硬编码域名为 email 验证创建了正则表达式。 But the domain name should be dynamic.但是域名应该是动态的。 I have passed the domain name as a parameter.我已将域名作为参数传递。 But I don't know how to pass parameter in regEx.但我不知道如何在正则表达式中传递参数。
But I tried this code, then I got the error " java.util.regex.PatternSyntaxException: Illegal repetition near index 12 ".但我尝试了这段代码,然后我得到了错误“ java.util.regex.PatternSyntaxException: Illegal repeat near index 12 ”。 I have followed some answers but it doesn't help for me.我遵循了一些答案,但这对我没有帮助。 From those answers I understood about repetition quantifier.从这些答案中,我了解了重复量词。 Can you tell me what I am missing here and how to solve this issue?你能告诉我我在这里缺少什么以及如何解决这个问题吗?
public static boolean validateEmail(String email, String domainName) {
pattern = Pattern.compile("^([\\w-\\.]+)@ {"+ domainName +"}" , Pattern.CASE_INSENSITIVE);
matcher = pattern.matcher(email);
return matcher.matches();
}
{
and }
have meaning in regex, namely for specifying how often the character before it can repeat. {
和}
在正则表达式中具有含义,即用于指定字符重复的频率。 Eg a{5}
matches aaaaa
.例如a{5}
匹配aaaaa
。
If you want to use curly braces in regex, you should escape them like \\{
and \\}
.如果你想在正则表达式中使用花括号,你应该像\\{
和\\}
一样转义它们。
But that's not what you need for passing this as a parameter — it will just be literal text at that point.但这不是您将其作为参数传递所需要的——此时它只是文字文本。 If you want to only match that literal domain, you could do Pattern.compile("^([\\w-\\.]+)@" + domainName, Pattern.CASE_INSENSITIVE)
.如果您只想匹配该文字域,则可以执行Pattern.compile("^([\\w-\\.]+)@" + domainName, Pattern.CASE_INSENSITIVE)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.