简体   繁体   English

正则表达式以匹配具有固定前缀和后缀的可变数量的作品

[英]Regular Expression to match variable number of works with fixed prefix and suffix

Sample input: Did xxx xxx xxx (could be any number of words) live or die? 输入样本:xxx xxx xxx(可以是任意数量的单词)是活着还是死了?

For example: 例如:

 Did   Michael      Jackson  live or     die     ?

I want to capture: Michael Jackson, live, die. 我要捕捉:迈克尔·杰克逊,活着,死了。 The sentence can have any number of spaces between words. 句子在词之间可以有任意数量的空格。

How do I do it? 我该怎么做?

Did\\s+(.+)\\s+(\\S+)\\s+or\\s+(\\S+)\\s*\\?

or am I missing something? 还是我错过了什么?

EDIT : changed single backslashes to double backslashes 编辑 :将单反斜杠更改为双反斜杠

Something like this would work. 这样的事情会起作用。 You will need to take the first group, Michael Jackson, and split it by the space character. 您需要参加第一个小组迈克尔·杰克逊(Michael Jackson),并按空格将其分开。

Pattern regex = Pattern.compile("^Did (.+)\s+(\w+)\s+or\s+(\w+)$", 
                                  Pattern.CASE_INSENSITIVE | 
                                  Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) 
{
  String []person = regexMatcher.group(0).split(" ");
  String action1 = regexMatcher.group(1);
  String action2 = regexMatcher.group(2);
} 

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

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