Bhanuprasad
Bhanuprasad

Reputation: 229

How to subString based on the special character?

I have String like below ,I want to get subString If any special character is there.

 String myString="Regular $express&ions are <patterns <that can@ be %matched against *strings";

I want out like below

       express
       inos
       patterns
       that
       matched
      Strings

Any one help me.Thanks in Advance

Upvotes: 2

Views: 6505

Answers (2)

Joffrey
Joffrey

Reputation: 37720

Note: as @MaxZoom pointed out, it seems that I didn't understand the OP's problem properly. The OP apparently does not want to split the string on special characters, but rather keep the words starting with a special character. The former is adressed by my answer, the latter by @MaxZoom's answer.


You should take a look at the String.split() method.

Give it a regexp matching all the characters you want, and you'll get an array of all the strings you want. For instance:

String myString = "Regular $express&ions are <patterns <that can@ be %matched against *strings";
String[] words = myString.split("[$&<@%*]");

Upvotes: 3

MaxZoom
MaxZoom

Reputation: 7763

This regex will select words that starts with special character:

[$&<%*](\w*)

explanation:

[$&<%*] match a single character present in the list below
   $&<%* a single character in the list $&<%* literally (case sensitive)
1st Capturing group (\w*)
  \w* match any word character [a-zA-Z0-9_]
   Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
g modifier: global. All matches (don't return on first match)

DEMO

MATCH 1 [9-16] express
MATCH 2 [17-21] ions
MATCH 3 [27-35] patterns
MATCH 4 [37-41] that
MATCH 5 [51-58] matched
MATCH 6 [68-75] strings

Solution in Java code:

String str = "Regular $express&ions are <patterns <that can@ be %matched against *strings";
Matcher matcher = Pattern.compile("[$&<%*](\\w*)").matcher(str);
List<String> words = new ArrayList<>();
while (matcher.find()) {
  words.add(matcher.group(1));
}
System.out.println(words.toString());

// prints [express, ions, patterns, that, matched, strings]

Upvotes: 3

Related Questions