我该如何编写一个正则表达式来接受任何输入字符串并只输出字母

How would I write a regex to take any input string and output only the letters?

本文关键字:字符 输入 任何 字符串 串并 输出 何编写 正则表达式 一个      更新时间:2023-09-26

如何编写正则表达式来接受任何输入字符串并仅输出字母?

输入:

'This is a sentence. &)$&(@#1232&()$123!!ª•º–ª§∞•¶§¢• This is an example of the input string. '

输出:

'thisisasentencethisisanexampleoftheinputstring'

您可以删除所有非字母,如下所示:

var input = 'This is a sentence. &)$&(@#1232&()$123!!ª•º–ª§∞•¶§¢• This is an example of the input string. ';
var output = input.replace(/[^a-zA-Z]/g, "");

如果您希望输出全部小写,那么在末尾添加.toLowerCase(),如下所示:

var output = input.replace(/[^a-zA-Z]/g, "").toLowerCase();

作为解释,此正则表达式匹配所有不是a-zA-Z的字符。regex末尾的g标志告诉它替换整个字符串中的所有字符串(而不仅仅是它找到的第一个匹配)。并且,""告诉它用一个空字符串替换每个匹配(有效地删除了所有匹配字符)。

var text = 'This is a sentence. &)$&(@#1232&()$123!!ª•º–ª§∞•¶§¢• This is an example of the input string. ';
text.replace(/[^a-z]/ig, '');