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

2 Answers 2

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("[!._,'@? ]+");
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.