I have text like this
Some. / text to-match (1)
I wanna replace ./()
for _
has next
Some_text_to_match_1
How do it the pattern?
You may trim the string from non-word chars on both ends (with .replaceAll("^\\\\W+|\\\\W+$", "")
), and then replace 1 or more non-word character chunks with _
inside the string (with .replaceAll("\\\\W+", "_")
):
String s = "Some. / text to-match (1)";
s = s.replaceAll("^\\W+|\\W+$", "").replaceAll("\\W+", "_");
System.out.println(s);
See the Java demo
Details :
\\W
matches a non-word character +
matches 1 or more occurrences of the subpattern this quantifier modifies. Since we need to use 2 different replacements when trimming the string and then replacing non-word chars inside it, we cannot use just 1 replaceAll
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.