正则表达式任意 ASCII 字符

匹配 xxx[any ASCII character here, spaces included]+xxx的正则表达式是什么?

我正在尝试 xxx[(\w)(\W)(\s)]+xxx,但它似乎不工作。

178751 次浏览

If you really mean any and ASCII (not e.g. all Unicode characters):

xxx[\x00-\x7F]+xxx

JavaScript example:

var re = /xxx[\x00-\x7F]+xxx/;


re.test('xxxabcxxx')
// true


re.test('xxx☃☃☃xxx')
// false

Try using .+ instead of [(\w)(\W)(\s)]+.

Note that this actually includes more than you need - ASCII only defines the first 128 characters.

. stands for any char, so you write your regex like this:

xxx.+xxx

Depending on what you mean with "ASCII character" you could simply try:

xxx.+xxx

Since US-ASCII characters are in the byte range of 0x00–0x7F (0–127):

xxx[\x00-\x7F]+xxx

You can use the [[:ascii:]] class.

[ -~]

It was seen here. It matches all ASCII characters from the space to the tilde.

So your implementation would be:

xxx[ -~]+xxx

Accepts / Matches only ASCII characters

/^[\x00-\x7F]*$/