2

I am trying split a string based on regular expression which contains "[.,?!]+'" all these characters including a single space but splitting is not happening?

Here's my class:

public class splitStr {
public static void main(String[] args)  {

        String S="He is a very very good boy, isn't he?";
        S.trim();
        if(1<=S.length() && S.length()<=400000){
        String delim ="[ .,?!]+'";
            String []s=S.split(delim);

        System.out.println(s.length);
for(String d:s)
{
    System.out.println(d);
}
        }
    }
}

3 Answers 3

2

The reason it's not working is because not all the delimiters are within the square brackets.

String delim ="[ .,?!]+'"; // you wrote this

change to this:

String delim ="[ .,?!']";
Sign up to request clarification or add additional context in comments.

Comments

1

Do the characters +, ', [ and ] must be part of the split?

I'm asking this because plus sign and brackets have special meaning in regular expressions, and if you want them to be part of the match, they must be escaped with \

So, if you want an expression that includes all these characters, it should be:

delim = "[\\[ .,\\?!\\]\\+']"

Note that I had to write \\ because the backslash needs to be escaped inside java strings. I'm also not sure if ? and + need to be escaped because they're inside brackets (test it with and without backslashes before them)

I'm not in a front of a computer right now, so I haven't tested it, but I believe it should work.

Comments

0
import java.util.*;
import java.util.stream.Collectors;

public class StringToken {
    public static void main(String[] args) {
        String S="He is a very very good boy, isn't he?";
        S.trim();
        if(1<=S.length() && S.length()<=400000){
            String delim = "[ .,?!']";
            String []s=S.split(delim);
            List<String> d = Arrays.asList(s);
           d= d.stream().filter(item-> (item.length() > 0)).collect(Collectors.toList());
            System.out.println(d.size());
            for(String m:d)
            {
                System.out.println(m);
            }
        }
    }
}

1 Comment

Please avoid code-only answers. Adding some introductory explanatory text will help others understand your answer better.

Your Answer

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