如何创建只在特定位置匹配字符串的java正则表达式模式?
我想创建一个正则表达式模式,只有当模式字符串不紧跟测试字符串或输入字符串中的任何其他字符串时,才能成功匹配!以下是我尝试过的:如何创建只在特定位置匹配字符串的java正则表达式模式?,java,regex,Java,Regex,我想创建一个正则表达式模式,只有当模式字符串不紧跟测试字符串或输入字符串中的任何其他字符串时,才能成功匹配!以下是我尝试过的: Pattern p = Pattern.compile("google.com");//I want to know the right format String input1 = "mail.google.com"; String input2 = "mail.google.com.co.uk"; Matcher
Pattern p = Pattern.compile("google.com");//I want to know the right format
String input1 = "mail.google.com";
String input2 = "mail.google.com.co.uk";
Matcher m1 = p.matcher(input1);
Matcher m2 = p.matcher(input2);
boolean found1 = m1.find();
boolean found2 = m2.find();//This should be false because "google.com" is followed by ".co.uk" in input2 string
任何帮助都将不胜感激 您的模式应该是
google\.com$
。$
字符与行尾匹配。详情请参阅
Pattern p = Pattern.compile("google\.com$");
美元符号表示它必须出现在被测试的行/字符串的末尾。还要注意的是,你的点将匹配任何字符,因此如果你想让它只匹配一个点,你需要转义它。你应该使用
google\.com$
<代码>$字符与行尾匹配
Pattern p = Pattern.compile("google\\.com$");//I want to know the right format
String input2 = "mail.google.com.co.uk";
Matcher m2 = p.matcher(input2);
boolean found2 = m2.find();
System.out.println(found2);
Output=
false
下面是如何匹配和获取不匹配的部分
以下是原始正则表达式模式,作为指向
^
-匹配字符串的开头(.*)
-捕获组中的所有内容,直到下一次匹配谷歌-匹配谷歌文字
\.
-必须使用\
com
-匹配com文本$
-匹配字符串的结尾
注意:在Java中,字符串文本中的
\
也必须转义^(.*)google\\\.com$
使用$
将匹配项绑定到字符串的末尾。