Mina F Mina F - 1 year ago 45
Java Question

How can I escape the \s (space char) from a string?

What I need is to escape each word in a string and escape each special char like: !,?._'@. What I've tried is this:

public class Solution
public static void main(String[] args)
Scanner scan = new Scanner(System.in);
Pattern pat = Pattern.compile("[!|,|?|.|_|'|@]");
String a = scan.nextLine();
String[] part = pat.split(a);
for(String p: part)

While this does escape the special characters, I can't manage to find a way to have the regex match the spaces between each word.
Also, I've tried using
after the regex.

For input like:
The dog is a very lazy dog, isn't he?

output should be:


Answer Source

[..] is character class which describes range for single character, not two characters (we can allow repetition of characters with quantifiers like + * {nim,max} but that is not the case here).

Also you don't need to use | inside [..] because there it is simple character, not OR operator. So [a|b] doesn't mean a OR b, it represents characters a | b (so any repetition of | like |c will represent another | and c).

Based on example you provided, you may be looking for:

Pattern pat = Pattern.compile("([!,?._'@]|\\s)+");

So you would need to use OR operator | outside of [..] and write \s as "\\s since \ is also special character in String literals (it can be used for instance to create tab \t) so it requires escaping.

I wrapped entire expression with (..) to create group which can represent all your delimiters. This allowed me to use + (quantifier representing "one or more occurrences") so now you regex can see ,. as single delimiter for split, which will ensure one split on entire expression containing few continuous delimiter, rather then splitting on each of delimiter individually, so instead of "a,.b" -> ["a, "", "b"] we can have ["a", "b"]