Reputation: 494
i have written a code in java as given under
public class sstring
{
public static void main(String[] args)
{
String s="a=(b+c); string st='hello adeel';";
String[] ss=s.split("\\b");
for(int i=0;i<ss.length;i++)
System.out.println(ss[i]);
}
}
and the output of this code is
a
=(
b
+
c
);
string
st
='
hello
adeel
';
what should i do in order to split =( or ); etc in two separate elements rather than single elements. in this array. i.e. my output may look as
a
=
(
b
+
c
)
;
string
st
=
'
hello
adeel
'
;
is it possible ?
Upvotes: 0
Views: 164
Reputation: 6332
Use this code there..
Pattern pattern = Pattern.compile("(\\w+|\\W)");
Matcher m = pattern.matcher("a=(b+c); string st='hello adeel';");
while (m.find()) {
System.out.println(m.group());
}
Upvotes: 1
Reputation: 109557
This matches with every find either a word \\w+
(small w) or a non-word character \\W
(capital W).
It is an unaccepted answer of can split string method of java return the array with the delimiters as well of the above comment of @RohitJain.
public String[] getParts(String s) {
List<String> parts = new ArrayList<String>();
Pattern pattern = Pattern.compile("(\\w+|\\W)");
Matcher m = pattern.matcher(s);
while (m.find()) {
parts.add(m.group());
}
return parts.toArray(new String[parts.size()]);
}
Upvotes: 2