匹配String中的模式

Edi*_*nda 0 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;
Run Code Online (Sandbox Code Playgroud)

Bra*_*raj 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
Run Code Online (Sandbox Code Playgroud)

模式说明:

  .*?                      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))
Run Code Online (Sandbox Code Playgroud)