繁体   English   中英

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

[英]Java Regex - Get all words before substring in String

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

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

谢谢。

这似乎有效:

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());
        }
    }
}

使用字符串操作:

int idx = sentence.indexOf(word);
if (idx < 0)
  throw new IllegalArgumentException("Word not found.");
String before = sentence.substring(0, idx);

使用正则表达式:

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());

或者:

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);

您需要在单词前后对句子的每个部分进行标记。

http://docs.oracle.com/javase/1.5.0/docs/api/

 String[] result = "this is a test".split("\\s"); //replace \\s with your word
 for (int x=0; x<result.length; x++)
     System.out.println(result[x]);

试试这个:

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

public class Test {
    public static void main(String[] args) {
        Pattern p = Pattern.compile("^.*?(?= word)");
        Matcher m = p.matcher("Everything before the word");
        while (m.find()) {
            System.out.println(m.group());
        }
    }
}

它分解如下:

。*? 一切

(?=之前

) 结束

原因是+是一个贪婪的量词,它将匹配整个字符串, 包括你指定的单词,而不会回馈。

如果你将它改为(\\\\w+?) word它应该有用(不情愿的量词)。 更多关于量词及其确切函数的信息

暂无
暂无

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

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