[英]Replace all characters not in range (Java String)
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"
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]"
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]
- 恰好匹配一个小写元音 [^aeiou]
- matches a character that ISN'T a lowercase vowel ( negated character class) [^aeiou]
- 匹配一个不是小写元音的字符( 否定字符类) ^[aeiou]
- matches a lowercase vowel anchored at the beginning of the line ^[aeiou]
- 匹配锚定在该行开头的小写元音 [^^]
- 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 - 在行的开头匹配除文字句点之外的任何内容,后跟“任意”字符 [az]
- matches exactly one character within the range of 'a'
to 'z'
(ie all lowercase letters) [az]
- 恰好匹配'a'
到'z'
范围内的一个字符(即所有小写字母) [az-]
- matches either an 'a'
, a 'z'
, or a '-'
(literal dash) [az-]
- 匹配'a'
, 'z'
或'-'
(文字破折号) [.*]*
- matches a contiguous sequence (possibly empty) of dots and asterisks [.*]*
- 匹配点和星号的连续序列(可能是空的) [aeiou]{3}
- matches 3 consecutive lowercase vowels (all not necessarily the same vowel) [aeiou]{3}
- 匹配3个连续的小写元音(所有元音都不一样) \\[aeiou\\]
- matches the string "[aeiou]"
\\[aeiou\\]
- 匹配字符串"[aeiou]"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.