Java Regex Help:在空格上拆分字符串,“=>”和逗号 [英] Java Regex Help: Splitting String on spaces, "=>", and commas
问题描述
我需要在以下任何一个序列上拆分字符串:
I need to split a string on any of the following sequences:
1个或多个空格
0个或更多个空格,后跟一个逗号,后跟0或更多空格,
0或更多空格,后跟=>,后跟0或更多空格
1 or more spaces
0 or more spaces, followed by a comma, followed by 0 or more spaces,
0 or more spaces, followed by "=>", followed by 0 or more spaces
Haven之前有过使用Java正则表达式的经验,所以我有点困惑。谢谢!
Haven't had experience doing Java regexs before, so I'm a little confused. Thanks!
示例:
添加r10,r12 => r10
存储r10 => r1
Example:
add r10,r12 => r10
store r10 => r1
推荐答案
只需创建匹配任意三种情况的正则表达式并将其传递给 split
方法:
Just create regex matching any of your three cases and pass it into split
method:
string.split("\\s*(=>|,|\\s)\\s*");
这里的正则表达式字面意思
Regex here means literally
- 零个或多个空格(
\\\\ *
) - 箭头,逗号或空格(
=> |,| \\\\
) - 零个或多个空格(
\\ s *
)
- Zero or more whitespaces (
\\s*
) - Arrow, or comma, or whitespace (
=>|,|\\s
) - Zero or more whitespaces (
\\s*
)
您可以替换空白 \\\\
(检测空格,制表符,换行符等),如有必要,请使用空格字符
。
You can replace whitespace \\s
(detects spaces, tabs, line breaks, etc) with plain space character if necessary.
这篇关于Java Regex Help:在空格上拆分字符串,“=>”和逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!