1

I'm trying to take in a String as an input, split it by the space character in order to store the words in an array, and then use those words to compare to other words. The problem is I would like for periods to be ignored during the split as the words they are being compared to will never contain a period.

For example:

String testString = "This. is. a. test. string.";
String[] test = testString.split(" ");

for (int i = 0; i < test.length; i++) {
    System.out.println(test[i]);
}

This will print out:

This.
is.
a.
test.
string.

Instead, I would like it to print out:

This
is
a
test
string

How can I ignore the period during the split?

2

4 Answers 4

5

How about

String[] test = testString.split("\\.[ ]*");

or

String[] test = testString.split("\\.\\s*");

or for more than one period (and ellipsis)

String[] test = testString.split("\\.+\\s*");
5
  • Use \s* to check for multiple spaces
    – Mason T.
    Feb 27, 2014 at 4:03
  • Although this is no longer wrong on the example input, it was just a single example. OP asked "I would like for periods to be ignored during the split." I don't see how this fits that requirement. For example, what about a sentence with an ellipsis...
    – mbroshi
    Feb 27, 2014 at 4:04
  • @mbroshi Couldn't you just then add a + after the .? Feb 27, 2014 at 4:05
  • I suppose this has become a nearly Talmudic discussion at this point. I will remove my downvote and let the OP sort things out him/herself.
    – mbroshi
    Feb 27, 2014 at 4:10
  • @user2310289 Thanks for the updated answers and explanation of regular expressions.
    – Jack
    Feb 27, 2014 at 22:58
1
String[] test = testString.split("\\.\\s*");
0
0

replace the dot inside the splitted string replace(".","");

String testString = "This. is. a. test. string.";
      String[] test = testString.split(" ");

      for (int i = 0; i < test.length; i++) {
          System.out.println(test[i].replace(".",""));
      }}
2
  • Why not remove them before? Does it make a difference? Feb 27, 2014 at 3:59
  • 1
    This places the "." in the String array.
    – Mason T.
    Feb 27, 2014 at 4:01
0
public class Main { 
    public static void main(String[] args) {
        String st = "This. is. a. test. string."";
        String[] tokens = st.split(".(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
        for(String t : tokens) {
            System.out.println("> "+t);
        }
    }
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.