分割标志:但不是::

huangapple go评论69阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年9月8日 07:34:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63785391.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定