使用正则表达式忽略子字符串

时间:2017-12-19 19:27:32

标签: java regex

我正在使用java并且有一个类似I am going to manchester的模式 我想使用正则表达式来匹配所有类型为I am going(某些字符串)to manchester的句子。 所以我的字符串i am going to manchester也会匹配I am going with my family to manchester

有谁知道正则表达式实现这一目标?

我尝试了以下但不起作用:

Pattern.compile("i am going (\\w+) to mancheter")

我正在使用PatternMatcher

1 个答案:

答案 0 :(得分:0)

试一试:

输入:

I am going with my family to manchester potato

输出:

I am going with my family to manchester

Java代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

// one class needs to have a main() method
public class HelloWorld {
 // arguments are passed using the text field below this editor
 public static void main(String[] args) {

  final String regex = "(<?I am going)(.+)(?>manchester)";
  final String string = "I am going with my family to manchester patata";

  final Pattern pattern = Pattern.compile(regex);
  final Matcher matcher = pattern.matcher(string);
  String answer = "";

  while (matcher.find()) {
   answer = matcher.group(0) + "";
  }


  System.out.println(answer);
 }
}