替换不在范围内的所有字符(Java 字符串)
如何替换字符串中不符合条件的所有字符。我在使用 NOT 运算符时遇到了麻烦。
具体来说,我正在尝试删除所有非数字字符,到目前为止我已经尝试过:
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"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解释一下:字符类开头的 ^ 会否定该类,但它必须位于该类内部才能起作用。字符类之外的相同字符是字符串/行开头的锚点。
你可以尝试这个:
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:
这是字符类定义及其如何与某些正则表达式元字符交互的快速备忘单。
[aeiou]
- 精确匹配一个小写元音[^aeiou]
- 匹配ISN'T小写元音的字符(否定 字符类)^[aeiou]
- 匹配位于行开头的小写元音[^^]
- 匹配不是caret/'^'
^[^^]
- 匹配行首不是插入符号的字符^[^.]。 - 匹配除文字句点之外的任何内容,后跟行首的“任意”字符
[az]
- 精确匹配范围内的一个字符>'a'
到'z'
(即全部小写字母)[az-]
- 匹配'a'
、'z'
或'-'
(文字破折号)[.*]*
- 匹配连续序列(可能为空)点和星号[aeiou]{3}
- 匹配 3 个连续的小写元音(不一定都是相同的元音)\[aeiou\]
- 匹配字符串"[aeiou]"
参考文献
相关问题
[01-12]
范围按预期工作?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'T a lowercase vowel (negated character 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 range of'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]"
References
Related questions
[01-12]
range work as expected?