แบ่งตาม: แต่ไม่ใช่ :: [ซ้ำ]

Sep 08 2020

ฉันสงสัยว่าฉันจะแยกสตริง:ได้อย่างไร แต่ไม่ได้::ใช้String#split(String)

ฉันใช้ Java ถ้ามันสร้างความแตกต่าง

ฉันมองไปรอบ ๆ ไม่พบอะไรเลยและฉันไม่คุ้นเคยกับ Regex ...

ตัวอย่าง:
coolKey:cool::valueควรกลับ["coolKey", "cool::value"]
cool::key:cool::valueควรกลับ["cool::key", "cool::value"]

คำตอบ

TimBiegeleisen Sep 08 2020 at 06:37

คุณสามารถลองแยก(?<!:):(?!:):

String input = "cool::key:cool::value";
String[] parts = input.split("(?<!:):(?!:)");
System.out.println(Arrays.toString(parts));

สิ่งนี้พิมพ์:

[cool::key, cool::value]

regex ที่ใช้ที่นี่บอกว่าจะแยกเมื่อ:

(?<!:)    the character which precedes is NOT colon
:         split on colon
(?!:)     which is also NOT followed by colon