0

I have a Task to split the columns out of a SQL Statement. This worked well for me with a simple Java split on ",". But now i have an issue with additional commas inside the column. I guess the answer to this problem is pretty simple, but it will not get into my mind.

Example:

Source:

"Col_A BIGINT , COL_B TIMESTAMP , COL_C DECIMAL(10,30) , COL_D VARCHAR(20)"

My wanted Output:

Array[0] = Col_A BIGINT
Array[1] = COL_B TIMESTAMP
Array[2] = COL_C DECIMAL(10,30)
Array[3] = COL_D VARCHAR(20)

The real (and abvious) output:

Array[0] = Col_A BIGINT
Array[1] = COL_B TIMESTAMP
Array[2] = COL_C DECIMAL(10
Array[3] = 30)
Array[4] = COL_D VARCHAR(20)

The Obvious Problem is the comma between the two decimals (COL_C).

Now i am asking you if there is a nice solution on this Problem. I really want to use a single split to receive the different columns. But how can i avoid the wrong split at the decimal description.

I hope you guys can understand my problem. English is not my native language.

3
  • 1
    You have spaces around ,, split(" , "). Else, use split("\\s*,\\s*(?![^)]*\\))") (it is more a work around that will fail with some input later, best is to use matching approach). Commented Aug 5, 2016 at 7:38
  • Could you give the code you are using for this output ? Commented Aug 5, 2016 at 7:40
  • Well the spaces were too obvious for me. My original statement is created by a DB2-Look. The spaces should be there every single time. I will give it a try, thanks for the reply Commented Aug 5, 2016 at 7:54

1 Answer 1

1

You just split the given string with regex : ,(?!\d)

Find the , which is not followed by digit.

Code sample:

System.out.println(Arrays.toString("Col_A BIGINT , COL_B TIMESTAMP , COL_C DECIMAL(10,30) , COL_D VARCHAR(20)".split(",(?!\\d)")));

Demo and Explaination of regex

Sign up to request clarification or add additional context in comments.

2 Comments

However, this still matches commas inside parentheses.
Yes. But according to OP parantheses always having number that is size of column.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.