ajm
ajm

Reputation: 13213

How do I split the string in java?

The string I want to split is as given below.

String text = "    *Some text*   *Another text* *Yet another text*        **last text**";

I need to split the above string so that I can get an array like below.

String[] array = {"Some text", "Another text", "Yet another text", "last text"}

If you notice, first three texts have single asterisk(*) around them, while the last one has double asterisk around it.

Also, texts can have spaces in between eg. *Some text*.

There will be not be any space between text and *

e.g. *Text* - will happen

*  some text * - will not happen

Can anyone help as I am not aware of regular expressions that much.

Upvotes: 0

Views: 72

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

Here are the specs deduced from your question and comments:

  • Initial * should be followed with a word char (letter/digit/underscore)
  • Trailing * should be preceded with a word char

You might use mere "\\B\\*\\b([^*]+)\\b\\*\\B" pattern that asserts the expected positions of the asterisks (\\B\\*\\b - asterisk after a non-word char or start of string and before a word char, and \\b\\*\\B - an asterisk before a non-word char/end of string and after a word char), and grabs 1 or more character other than * into Group 1.

String s = "    *Some text*   *Another text* *Yet another text*        **last text**";
Pattern pattern = Pattern.compile("\\B\\*\\b([^*]+)\\b\\*\\B");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    System.out.println(matcher.group(1)); 
} 

A more complex variation to only check if the asterisks are followed/preceded or not with whitespaces (start|space+*+non-space+any_chars_not_parens+non-space+*+space|end) can be

"(?<!\\S)\\*(?!\\s)([^*]+)(?<!\\s)\\*(?!\\S)"

See another Java demo

Upvotes: 1

Related Questions