java - Regex to keep null input


Keywords:java 


Question: 

I a currently working on a program that splits a full sentence string into an array of string by words, whitespace, and punctuation. However I also want to be able to make the program do something if the sentence that was inputed is null. Currently my regular expression that I have is throwing out any null input. The expression is:

String[] fragments = sentence.split("(?<=\\b|[^\\p{L}])");

Is there a way to modify this regular expression so that if it comes across a null input, the array will contain that null value so it can be processed later in the program?


1 Answer: 

String[] fragments = (sentence == null) ? null : sentence.split("(?<=\\b|[^\\p{L}])");

Given your requirement, this should

  • return null if input is null.
  • return an array with a single entry of "" if input is "".
  • return the array as expected if not "" nor null.