替换所有不在范围内的字符(Java 字符串)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3847294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace all characters not in range (Java String)
提问by Chris Dutrow
How do you replace all of the characters in a string that do not fit a criteria. I'm having trouble specifically with the NOT operator.
如何替换字符串中不符合条件的所有字符。我在使用 NOT 运算符时遇到了问题。
Specifically, I'm trying to remove all characters that are not a digit, I've tried this so far:
具体来说,我正在尝试删除所有不是数字的字符,到目前为止我已经尝试过:
String number = "703-463-9281";
String number2 = number.replaceAll("[0-9]!", ""); // produces: "703-463-9281" (no change)
String number3 = number.replaceAll("[0-9]", ""); // produces: "--"
String number4 = number.replaceAll("![0-9]", ""); // produces: "703-463-9281" (no change)
String number6 = number.replaceAll("^[0-9]", ""); // produces: "03-463-9281"
采纳答案by tangens
To explain: The ^ at the start of a character class will negate that class But it has to be inside the class for that to work. The same character outside a character class is the anchor for start of string/line instead.
解释一下:字符类开头的 ^ 将否定该类,但它必须在类内部才能起作用。字符类之外的相同字符是字符串/行开头的锚点。
You can try this instead:
你可以试试这个:
"[^0-9]"
回答by polygenelubricants
Here's a quick cheat sheet of character class definition and how it interacts with some regex meta characters.
这是字符类定义的快速备忘单,以及它如何与一些正则表达式元字符交互。
[aeiou]- matches exactly one lowercase vowel[^aeiou]- matches a character that ISN'Ta lowercase vowel (negatedcharacter class)^[aeiou]- matches a lowercase vowel anchored at the beginning of the line[^^]- matches a character that isn't a caret/'^'^[^^]- matches a character that isn't a caret at the beginning of line^[^.].- matches anything but a literal period, followed by "any" character, at the beginning of line[a-z]- matches exactly one character within the rangeof'a'to'z'(i.e. all lowercase letters)[az-]- matches either an'a', a'z', or a'-'(literal dash)[.*]*- matches a contiguous sequence (possibly empty) of dots and asterisks[aeiou]{3}- matches 3 consecutive lowercase vowels (all not necessarily the same vowel)\[aeiou\]- matches the string"[aeiou]"
[aeiou]- 正好匹配一个小写元音[^aeiou]- 匹配一个不是小写元音的字符(否定字符类)^[aeiou]- 匹配定位在行首的小写元音[^^]- 匹配一个不是插入符号的字符/'^'^[^^]- 匹配行首不是插入符号的字符^[^.].- 匹配除文字句点外的任何内容,后跟“任何”字符,在行的开头[a-z]-在中匹配一个字符范围的'a'给'z'(即所有小写字母)[az-]- 匹配 an'a'、a'z'或 a'-'(文字破折号)[.*]*- 匹配点和星号的连续序列(可能为空)[aeiou]{3}- 匹配 3 个连续的小写元音(不一定都是相同的元音)\[aeiou\]- 匹配字符串"[aeiou]"

