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
  • 85,076
  • 16
  • 154
  • 332
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: `"(?:(?<!^|[^.]|)|(?=[.])|\\s+)"`. – 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
  • 69,796
  • 4
  • 95
  • 132
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
  • 5,107
  • 1
  • 20
  • 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,109
  • 6
  • 17