这似乎有效:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Pattern p = Pattern.compile("([\\w\\s]+) word");
Matcher m = p.matcher("Could you test a phrase with some word");
while (m.find()) {
System.err.println(m.group(1));
System.err.println(m.group());
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用字符串操作:
int idx = sentence.indexOf(word);
if (idx < 0)
throw new IllegalArgumentException("Word not found.");
String before = sentence.substring(0, idx);
Run Code Online (Sandbox Code Playgroud)
使用正则表达式:
Pattern p = Pattern.compile(Pattern.quote(word));
Matcher m = p.matcher(sentence);
if (!m.find())
throw new IllegalArgumentException("Word not found.");
String before = sentence.substring(0, m.start());
Run Code Online (Sandbox Code Playgroud)
或者:
Pattern p = Pattern.compile("(.*?)" + Pattern.quote(word) + ".*");
Matcher m = p.matcher(sentence);
if (!m.matches())
throw new IllegalArgumentException("Word not found.");
String before = m.group(1);
Run Code Online (Sandbox Code Playgroud)