正则表达式匹配任何单个字符(仅一个字符) [英] regex match any single character (one character only)
问题描述
如何用正则表达式匹配任意一个字符?
How do you match any one character with a regular expression?
我正在写这个问题和以下答案以供一般参考.Stack Overflow 上的许多其他问题听起来像是承诺快速回答,但实际上是在问一些更具体的问题.
I am writing this question and the following answer for a general reference. A number of other questions on Stack Overflow sound like they promise a quick answer, but are actually asking something more specific.
推荐答案
匹配任意单个字符
- 使用点
.
字符作为通配符来匹配任何单个字符. - Use the dot
.
character as a wildcard to match any single character.
Match any single character
示例正则表达式:a.c
abc // match
a c // match
azc // match
ac // no match
abbc // no match
匹配集合中的任何特定字符
- 使用方括号
[]
匹配集合中的任何字符. - 使用
\w
匹配任何单个字母数字字符:0-9
、az
、AZ
和_
(下划线). - 使用
\d
匹配任何一位数字. - 使用
\s
匹配任何单个空白字符. - Use square brackets
[]
to match any characters in a set. - Use
\w
to match any single alphanumeric character:0-9
,a-z
,A-Z
, and_
(underscore). - Use
\d
to match any single digit. - Use
\s
to match any single whitespace character.
Match any specific character in a set
示例 1 正则表达式:a[bcd]c
Example 1 regex: a[bcd]c
abc // match
acc // match
adc // match
ac // no match
abbc // no match
示例 2 正则表达式:a[0-7]c
Example 2 regex: a[0-7]c
a0c // match
a3c // match
a7c // match
a8c // no match
ac // no match
a55c // no match
匹配任何字符除了 ...
使用方括号中的帽子 [^]
匹配除帽子^
之后的任何字符之外的任何单个字符.
Match any character except ...
Use the hat in square brackets [^]
to match any single character except for any of the characters that come after the hat ^
.
示例正则表达式:a[^abc]c
aac // no match
abc // no match
acc // no match
a c // match
azc // match
ac // no match
azzc // no match
(不要将 [^]
中的 ^
与其作为行首字符的其他用法混淆:^
= 行开始,$
= 行结束.)
(Don't confuse the ^
here in [^]
with its other usage as the start of line character: ^
= line start, $
= line end.)
在任何字符后使用可选字符 ?
指定该字符出现零次或一次.因此,您可以使用 .?
来匹配任意单个字符.
Use the optional character ?
after any character to specify zero or one occurrence of that character. Thus, you would use .?
to match any single character optionally.
示例正则表达式:a.?c
abc // match
a c // match
azc // match
ac // match
abbc // no match
另见
- 教您正则表达式基础知识的快速教程
- 一个可以尝试的练习沙盒
这篇关于正则表达式匹配任何单个字符(仅一个字符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!