简体   繁体   English

如何创建一个只在某个位置匹配字符串的java正则表达式模式?

[英]How to create a java regular expression pattern that would match a string only at certain positon?

I would like to create a regular expression pattern that would succeed in matching only if the pattern string not followed by any other string in the test string or input string ! 我想创建一个正则表达式模式, 只有当模式字符串后面跟着测试字符串或输入字符串中的任何其他字符串时才能成功匹配! Here is what i tried : 这是我试过的:

      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

Any help would be appreciated! 任何帮助,将不胜感激!

Your pattern should be google\\.com$ . 你的模式应该是google\\.com$ The $ character matches the end of a line. $字符匹配一行的结尾。 Read about regex boundary matchers for details. 阅读有关正则表达式边界匹配器的详细信息。

Here is how to match and get the non-matching part as well. 以下是匹配和获取非匹配部分的方法。

Here is the raw regex pattern as an interactive link to a great regular expression tool 这是原始正则表达式模式,作为一个伟大的正则表达式工具的交互式链接

^(.*)google\\.com$

^ - match beginning of string ^ - 匹配字符串的开头
(.*) - capture everything in a group up to the next match (.*) - 捕捉一组中的所有内容直到下一场比赛
google - matches google literal 谷歌 - 匹配谷歌文字
\\. - matches the . - 匹配. literal has to be escaped with \\ 文字必须用\\
com - matches com literal com - 匹配com literal
$ - matches end of string $ - 匹配字符串的结尾

Note: In Java the \\ in the String literal has to be escaped as well! 注意:在Java中,字符串文字中的\\也必须进行转义! ^(.*)google\\\\.com$

Pattern p = Pattern.compile("google\.com$");

The dollar sign means it has to occur at the end of the line/string being tested. 美元符号表示它必须出现在正在测试的行/字符串的末尾。 Note too that your dot will match any character, so if you want it to match a dot only, you need to escape it. 另请注意,您的点将匹配任何字符,因此如果您希望它只匹配一个点,则需要将其转义。

You should use google\\.com$ . 你应该使用google\\.com$ $ character matches the end of a line. $ character匹配一行的结尾。

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 输出= false

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

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