我想分割一个字符串,只要它包含字符“ - ”或者它包含一个空格,但只有在“ - ”或空格之前和之后存在一个字符。
示例:
" test" -> Dont split
"-test" -> Dont split
"test test" -> split
" test test" -> split
"test-" -> dont split
"test-test" -> split
"a-test" -> split
答案 0 :(得分:6)
此RegEx与任何"匹配"或" - " (或更多处理多个空格或短划线)由单词字符包围。
(?<=\w)[ -]+(?=\w)
final String regex = "(?<=\\w)[ -]+(?=\\w)";
System.out.println(Arrays.toString(" test".split(regex)));
System.out.println(Arrays.toString("-test".split(regex)));
System.out.println(Arrays.toString("test test".split(regex)));
System.out.println(Arrays.toString(" test test".split(regex)));
System.out.println(Arrays.toString("test-".split(regex)));
System.out.println(Arrays.toString("test-test".split(regex)));
System.out.println(Arrays.toString("a-test".split(regex)));
[ test]
[-test]
[test, test]
[ test, test]
[test-]
[test, test]
[a, test]