Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split comma-separated string but exclude some words containing comma in Java

Tags:

java

string

regex

Assume that we have below string:

"test01,test02,test03,exceptional,case,test04"

What I want is to split the string into string array, like below:

["test01","test02","test03","exceptional,case","test04"]

How can I do that in Java?

like image 373
macemers Avatar asked Oct 20 '25 06:10

macemers


1 Answers

This negative lookaround regex should work for you:

(?<!exceptional),|,(?!case)

Working Demo

Java Code:

String[] arr = str.split("(?<!exceptional),|,(?!case)");

Explanation:

This regex matches a comma if any one of these 2 conditions meet:

  1. comma is not preceded by word exceptional using negative lookbehind (?<!exceptional)
  2. comma is not followed by word case using negative lookahead (?!case)

That effectively disallows splitting on comma when it is surrounded by exceptional and case on either side.

like image 72
anubhava Avatar answered Oct 21 '25 22:10

anubhava