我需要删除给定字符串中的所有字符,除了应该留下的几个字符.如何用regexp做到这一点?
简单测试:不应删除字符[1,a,*],所有其他字符应来自字符串"asdf123**".
Jon*_*eet 22
在集合中有:^.
你应该可以这样做:
text = text.replaceAll("[^1a*]", "");
Run Code Online (Sandbox Code Playgroud)
完整样本:
public class Test
{
public static void main(String[] args)
{
String input = "asdf123**";
String output = input.replaceAll("[^1a*]", "");
System.out.println(output); // Prints a1**
}
}
Run Code Online (Sandbox Code Playgroud)
当内部使用[和]的^(脱字符号)是not操作员.
它是这样使用的:
"[^abc]"
Run Code Online (Sandbox Code Playgroud)
这将匹配除a bor 之外的任何字符c.