如何使用单个正则表达式来分割 Java 中的以下所有文本。
<ab>::=<cd> <ef>|<gh> => ['<ab>', '<cd> <ef>', '<gh>']
<ri>::=hello|nope|we|super => ['<ri>', 'hello', 'nope', 'we', 'super']
<ri>::= hello | nope | we |super => ['<ri>', 'hello', 'nope', 'we', 'super']
最佳答案
正如 Rawing 在评论中所建议的,您可以在 ::=
和管道符号上拆分。为了确保您直接修剪空格,我建议如下:\s*\|\s*
。这会将 |
与其前后任意数量的空格(包括空格)相匹配。因此,当对其进行拆分时,空格也会被删除。
现在要将它们组合起来,请将它们放入捕获组中并用 or 分隔它们:
(::=|\s*\|\s*)
查看该组捕获了什么 here
绿色标记的部分是 split 的部分,“正常”部分是 split 的结果。
关于Java 正则表达式谜题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47071665/