我想在空格上分割短语,而不是在带引号的字符串中分隔空格(即双引号对中的字符串").
例如:
software term "on the fly" and "synchrony"
Run Code Online (Sandbox Code Playgroud)
应分为以下5个部分:
software
term
on the fly
and
synchrony
Run Code Online (Sandbox Code Playgroud)
那我怎么能在java中实现呢?
这个正则表达式为您实现了拆分,并清除了任何定界引号:
String[] terms = input.split("\"?( |$)(?=(([^\"]*\"){2})*[^\"]*$)\"?");
Run Code Online (Sandbox Code Playgroud)
它通过拆分空间来工作,但前提是后跟偶数引号.
引号本身已被消耗,因此它们不会在输出中结束,方法是将它们包含在分割项中.需要
该术语( |$)来捕获尾随引用.
请注意,如果可以引用第一个术语,则需要先清除该引号:
String[] terms = input.replaceAll("^\"", "").split("\"?( |$)(?=(([^\"]*\"){2})*[^\"]*$)\"?");
Run Code Online (Sandbox Code Playgroud)
测试代码:
String input = "software term \"on the fly\" and \"synchron\"";
String[] terms = input.split("\"?( |$)(?=(([^\"]*\"){2})*[^\"]*$)\"?");
System.out.println(Arrays.toString(terms));
Run Code Online (Sandbox Code Playgroud)
输出:
[software, term, on the fly, and, synchron]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2473 次 |
| 最近记录: |