Java Regex - 获取String中子字符串之前的所有单词

cra*_*ool 5 java regex string substring

我有一个包含一个句子的字符串,我希望根据一个单词将它分成两半.我有正则表达式(\\w+) word,我认为它会在"单词"+"单词"本身之前得到所有单词,然后我可以删除最后四个字符.

然而这似乎不起作用..任何想法我做错了什么?

谢谢.

Gui*_*let 9

这似乎有效:

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)


eri*_*son 5

使用字符串操作:

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)