suppose I have a string
String = ".... helllo.... good \"morning\" .....\" "
I want to get output as
helllo good morning
How can I do that using regular expression in Java?
suppose I have a string
String = ".... helllo.... good \"morning\" .....\" "
I want to get output as
helllo good morning
How can I do that using regular expression in Java?
If you're just trying to remove the .
and the "
, then you can do
str = str.replaceAll("\"|\\.", "");
This regular expression replaces any "
(escaped as \"
because in a java string literal) or (|
) .
(escaped first as \.
because in a regex then as \\.
because a \
must be escaped in a java string literal) by nothing (""
).
Supposing you just want to maintain the space character and letters, you can use the following regex:
[^a-zA-Z\s]+
If you also want to include numbers:
[^a-zA-Z0-9\s]+
Just replace the matches of that regular expression by an empty string.
Edit:
If you just want to do the opposite (remove certain characters, like .
and "
), then you can check @dystroy
answer.
This
String yourString = ".... helllo.... good \"morning\" .....\" ";
System.out.println(yourString.replaceAll("[.\\\"]", ""));
outputs helllo good morning
public static void main(String[] args) {
String str = ".... helllo.... good \"morning\" .....\" ";
str = str.replaceAll("[^a-zA-Z]", " ").replaceAll(" +", " ");
System.out.println(str);
}
There are many ways to do this.
Here is a way to do it using simple replace methods of String class.
String s = ".... helllo.... good \"morning\" .....\" ";
s = s.replace(".","").replace("\"", "");
System.out.println(s);