英文:
Split by : but not ::
问题
我在想如何使用 String#split(String)
方法按 :
分割字符串,但不包括 ::
。
我在使用 Java,如果有差异的话。
我查了很多资料,但没有找到合适的内容,而且我对正则表达式不熟悉。
示例:
coolKey:cool::value
应该返回 ["coolKey", "cool::value"]
cool::key:cool::value
应该返回 ["cool::key", "cool::value"]
英文:
I was wondering how I could split a String by :
but not ::
using String#split(String)
I am using Java if it makes a difference.
I looked around a lot and I couldn't find anything, and I'm not familiar with Regex...
Example:
coolKey:cool::value
should return ["coolKey", "cool::value"]
cool::key:cool::value
should return ["cool::key", "cool::value"]
答案1
得分: 0
你可以尝试使用 (?<!:):(?!:)
进行分割:
String input = "cool::key:cool::value";
String[] parts = input.split("(?<!:):(?!:)");
System.out.println(Arrays.toString(parts));
这将打印出:
[cool::key, cool::value]
这里使用的正则表达式表示在以下情况进行分割:
(?<!:)
:前面的字符不是冒号:
:以冒号进行分割(?!:)
:后面的字符也不是冒号
英文:
You could try splitting on (?<!:):(?!:)
:
String input = "cool::key:cool::value";
String[] parts = input.split("(?<!:):(?!:)");
System.out.println(Arrays.toString(parts));
This prints:
[cool::key, cool::value]
The regex used here says to split when:
(?<!:) the character which precedes is NOT colon
: split on colon
(?!:) which is also NOT followed by colon
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论