用于传递 space 和单引号的正则表达式
RegEx for passing space and single quote
我对 RegEx 还很陌生,在让我的 RegEx 执行我想要的操作时遇到了一些问题。我正在尝试创建一个 RegEx,以防止除单引号 (')、破折号 (-) 和句点 (.) 之外的任何特殊字符。
RegEx 需要允许空格和空字符串。
我现在拥有的是:
^[a-zA-Z0-9-.]*$
我需要添加什么才能使其正常工作,例如名称 "Kevin O'Leary"?
我试图通过添加 \s 来允许空格,但它破坏了我的 RegEx 的其他部分。
^[a-zA-Z0-9-.]*$
预期:应该允许像 Kevin O'Leary 这样的名字
实际:不允许像 Kevin O'Leary
这样的名字
只需在字符范围内添加一个引号和一个space:
^[ a-zA-Z0-9'.-]*$
space 可以简单地是模式中的文字 space。此外,您需要将 -
作为最后一个符号,因为它在范围内具有特殊含义。
您可以使用 i
标志并使用此表达式:
^[a-z0-9'-.\s]+$
其中 \x27
是 '
,\s
是 space。
const regex = /^[a-z0-9'-.\s]+$/gmi;
const str = `Kevin O'Leary`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
DEMO
正则表达式
如果不需要这个表达式,它可以是 regex101.com 中的 modified/changed。
正则表达式电路
jex.im 可视化正则表达式:
我对 RegEx 还很陌生,在让我的 RegEx 执行我想要的操作时遇到了一些问题。我正在尝试创建一个 RegEx,以防止除单引号 (')、破折号 (-) 和句点 (.) 之外的任何特殊字符。 RegEx 需要允许空格和空字符串。
我现在拥有的是:
^[a-zA-Z0-9-.]*$
我需要添加什么才能使其正常工作,例如名称 "Kevin O'Leary"?
我试图通过添加 \s 来允许空格,但它破坏了我的 RegEx 的其他部分。
^[a-zA-Z0-9-.]*$
预期:应该允许像 Kevin O'Leary 这样的名字 实际:不允许像 Kevin O'Leary
这样的名字只需在字符范围内添加一个引号和一个space:
^[ a-zA-Z0-9'.-]*$
space 可以简单地是模式中的文字 space。此外,您需要将 -
作为最后一个符号,因为它在范围内具有特殊含义。
您可以使用 i
标志并使用此表达式:
^[a-z0-9'-.\s]+$
其中 \x27
是 '
,\s
是 space。
const regex = /^[a-z0-9'-.\s]+$/gmi;
const str = `Kevin O'Leary`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
DEMO
正则表达式
如果不需要这个表达式,它可以是 regex101.com 中的 modified/changed。
正则表达式电路
jex.im 可视化正则表达式: