0

if in my String two regex are continuous [comma(,) and space( )] so I want to treat one regex so what should I do.

String s = "He is a very very good boy, isn't he?";
String str[]=s.split("[!._,'@? ]");

My output is:-

11
He
is
a
very
very
good
boy
space( )
isn
t
he

I want this:-

10
He
is
a
very
very
good
boy
isn
t
he
Deepshika S
  • 500
  • 4
  • 16

2 Answers2

3

Consume both tokens on the split, just add + to your pattern to indicate that it should match one or more; like,

String[] str = s.split("[!._,'@? ]+");
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

You can achieve the same result with StringTokenizer as well. Here is the code segment:-

StringTokenizer str = new StringTokenizer(s," !@,.?_'");
    System.out.println(str.countTokens());
    while(str.hasMoreTokens()) {
        System.out.println(str.nextToken());
}

To know the difference between StringTokenizer and split() check this link

shankar upadhyay
  • 883
  • 12
  • 18