Reputation: 196
Sirs,
I am working in Java Netbeans. I am trying to split a string (into an array of Strings) using a regular expression. Essentially, if a user enters:
Hello World <5> How are you < yahoo > google!
into a jTextArea, I want the string above entered into an array called arrayOfStringsToProcess
for further processing. At the end of the sequence, the values of arrayOfStringsToProcess
should be:
{"Hello World", "5" , "How are you", "yahoo", "google!"}
I'm indifferent to whether or not there is a newline character in there.
When I try (in netbeans):
String inputFromTextField = "";
String regularExpressionToSplit = "<>";
String[] arrayOfStringsToProcess;
inputFromTextArea = jTextArea23.getText();
arrayOfStringsToProcess = inputFromTextArea.split(regularExpressionToSplit);
the code compiles and executes, but the entire string fetched from jTextArea23
is loaded into the 0th element of the arrayOfStringsToProcess
as if no splitting ever took place.
As far as I am aware, the code I have above does the job just fine outside of netbeans, but netbeans simply does not want to split the string against the regular expression.
Lastly, when I reduce the "regular expression" to a single delimiting character, such as "<"
netbeans will split the string this way:
{"Hello World", "5> How are you", "yahoo> google!"}
Obviously, this code compiles and executes, but doesn't produce the output that I want.
Is there a way of doing this in Java netbeans without resorting to nonsense such as counting the number of <
and >
in the string, and splitting the string up one at a time? I have no way of knowing in advance how many of these characters the user is going to enter into jTextArea23.
I'm sure this exact question has been asked somewhere and the answer is out there. I just don't really know what keywords to use in my search. Any help would be appreciated,
Brent.
Upvotes: 0
Views: 1072
Reputation: 137104
The pattern you need to use needs to say: I want to split at >
or <
. This is expressed in a regular expression with the |
character. So you can use the pattern <|>
. Note that if you want to split around the spaces also, you can add \\s*
to match zero or more spaces.
public static void main(String[] args) {
String str = "Hello World <5> How are you < yahoo > google!";
String[] tokens = str.split("\\s*<\\s*|\\s*>\\s*");
System.out.println(Arrays.toString(tokens)); // prints "[Hello World, 5, How are you, yahoo, google!]"
}
Upvotes: 1
Reputation: 124235
Your current regex <>
represents exactly string "<>"
. If you want to split on either <
or >
then:
you are looking for OR
operator which is represented by |
split("<|>")
you could also use character class
split("[<>]")
Upvotes: 0