匹配String中的模式

时间:2014-07-21 20:14:37

标签: java regex string

不知道怎么更正确地问,所以会尽我所能。

我们正在搜索一个示例字符串,另一个模式字符串:

  • 它的长度== 3,
  • 第一个字符是' b',
  • 第三个字符也是' b'。

我需要一些方法来弄清楚示例是否包含模式(我想到的是像example.indexOf(pattern)> - 1)

Pattern = "b*b"
Example = "gjsdng" - false;
Example = "bob" - true;
Example = "bab" - true;
Example = "gdfgbUbfg" - true;

3 个答案:

答案 0 :(得分:5)

您可以使用String#matches(regex)方法和.*?b.b.*正则表达式匹配文字。

System.out.println("gjsdng".matches(".*?b.b.*"));    //false
System.out.println("bob".matches(".*?b.b.*"));       //true
System.out.println("bab".matches(".*?b.b.*"));       //true
System.out.println("gdfgbUbfg".matches(".*?b.b.*")); // true

模式说明:

  .*?                      any character except \n (0 or more times
                           (matching the least amount possible))
  b                        'b'
  .                        any character except \n
  b                        'b'
  .*                       any character except \n (0 or more times
                           (matching the most amount possible))

答案 1 :(得分:0)

.*b[A-Za-z]b.*是您正在寻找的正则表达式模式。

  • b字母b在字符1的格式
  • [A-Za-z]模式
  • 的字符2中的任何字母A-Z或a-z
  • b字母b位于模式

    的字符3中
    System.out.println("bobby".matches(".*b[A-Za-z]b.*")); // true
    System.out.println("gjsdng".matches(".*b[A-Za-z]b.*")); // false
    System.out.println("bob".matches(".*b[A-Za-z]b.*")); // true
    System.out.println("bab".matches(".*b[A-Za-z]b.*")); // true
    System.out.println("gdfgbUbfg".matches(".*b[A-Za-z]b.*")); // true
    

http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

答案 2 :(得分:0)

Brrrrr。

绝对不需要多次创建Pattern。只需编译一次:

Pattern pattern = Pattern.compile( "b.b" );

此外,不需要匹配整个String。只是找到一个搜索过的String。所以这就是你要找的东西:

assertFalse( pattern.matcher( "Gollum" ).find() );
assertTrue( pattern.matcher( "bob" ).find() );
assertTrue( pattern.matcher( "babe" ).find() );
assertTrue( pattern.matcher( "Alibaba" ).find() );
相关问题