0

I am relatively new to java and I have to create a pig latin translator for a phrase. Here's the code I have right now so that I can split the phrase that the user would enter. Sorry for the improper formatting.

String english = "Queen of all reptiles";
String[] words = english.split ("\\s+"); 
for (int i = 0 ; i < words.length ; i++) {
    System.out.println (words [i]);
}

The output for this code is:

Queen   
of    
all   
reptiles   

However, I would like to split the String english by spaces and special characters so that if

String english  = "Queen. of reptiles."

it would output:

Queen   
.   
of   
reptiles  
.

I attempted to do this: String[] words = english.split ("[^a-zA-Z0-9]", ""); but it does not work.

Luiggi Mendoza
  • 83,472
  • 15
  • 149
  • 315
user3618754
  • 13
  • 1
  • 3
  • 1
    Not sure why you would use such complex regex when you may use `Pattern` and `Matcher` with a regex like `(\\w+|\\.)` and find every `String` in your current `String` and add all the elements in a `List` (more code verbosity but easier to maintain). Note: the *complex* regex was in an already deleted answer: `"(?:(? – Luiggi Mendoza May 09 '14 at 02:25

3 Answers3

3

You can use the following for your string case.

String s  = "Queen. of reptiles.";
String[] parts = s.split("(?=\\.)|\\s+");
System.out.println(Arrays.toString(parts));

Output

[Queen, ., of, reptiles, .]
hwnd
  • 67,942
  • 4
  • 86
  • 123
0

There seems to be a discussion of using split along with look-behinds to achieve this here:

How to split a string, but also keep the delimiters?

Community
  • 1
  • 1
Zeki
  • 4,877
  • 1
  • 18
  • 27
0

As Luiggi Mendoza described in his comment, this will work as you described:

String english = "Queen. of reptiles.";
Pattern p = Pattern.compile("\\w+|\\.");
Matcher m = p.matcher(english);

do {
   if (m.find()) {
      System.out.println(m.group());
   }
} while (!m.hitEnd());
Jeff Ward
  • 1,052
  • 6
  • 17