Java - 正则表达式分割输入文本但保留分隔符

时间:2013-04-08 12:49:49

标签: java regex

寻找一些正则表达式的帮助。我正在寻找一种Java方法,用文字分割一些输入文本,但也保留分隔符(空格,标点符号)。另一种方法是将单词拆分为自己的索引,其他非单词字符也可以放在数组的其他索引中。

此输入文字:

"Hello, this isn't working!"

应该放入这样的数组中:

{"Hello", ",", "this", "isn't", "working", "!"}

{"Hello", ", ", "this", " ", "isn't", " ", "working", "!"}

我用Python完成了基本相同的事情:

def split_input(string):
    return re.findall(r"[\w']+|[\s.,!?;:-]", string)

但我还没有找到一种在Java中完成同样事情的方法。我已经尝试了String.split()前瞻/后视,我尝试了模式匹配器,但没有太多运气。

非常感谢任何帮助!

4 个答案:

答案 0 :(得分:5)

split不是Python的findall的Java模拟。 Matcher.find是。

Pattern stuff = Pattern.compile("[\\w']+|[\\s.,!?;:-]");
Matcher matcher = stuff.matcher("Hello, this isn't working!");
List<String> matchList = new ArrayList<String>();
while (matcher.find()) {
    matchList.add(matcher.group(0)); // add match to the list
}

答案 1 :(得分:1)

试试这个:这正是你想要的。

public static void main(String[] args) {
    String str = "Hello, this isn't working!";
    String[] s = str.split("(?<=\\s+|,\\s)");
    System.out.println(Arrays.toString(s));
}

输出:

[Hello, , this , isn't , working!]

答案 2 :(得分:0)

所以,抛开你的奇怪例子,这里的东西应该适合你的需要(还有待测试):

"(?=[\\w']+|[\\s.,!?;:-])"

第一个版本。

"(?=[\\w']+|[\\s.,!?;:-]+)"

要保留几个分隔符。

整个想法是,因为你想要拆分但保留所有角色,只能匹配位置。

答案 3 :(得分:0)

也许不是最好的方法,但你可以尝试:

string.replaceAll("([\\s.,!?;:-])", "$1\n");
string.split("\n");
相关问题