首页 > 解决方案 > 如何在 RegEx 对象中使用元字符 /w

问题描述

在下面的示例中,我想测试一个字符串是否包含允许的字符。但是我没有得到预期的结果。我错过了什么?

const string = 'sdf^&&*^%^';

const pattern = "\\w";
const allowed = new RegExp(pattern);

const pattern2 = "\w";
const allowed2 = new RegExp(pattern);

const pattern3 = /\w/g;

document.getElementById("app").innerHTML = `
<p>This should be false (but is true): ${allowed.test(string)}</p>
<p>This should be false (but is true): ${allowed.test(string)}</p>
<p>This should be false (works): ${string.match(pattern3)}</p>
`;

- - - - - - 编辑:

原来前面的解释很混乱。也许这可以清除它。

在我的代码中,正则表达式模式通过属性(在 React 中)传递给子组件。所以不可能通过使用正则表达式本身来传递它。所以也许问题更多:

“如何使用字符串中的正则表达式模式来匹配单个单词 az、AZ、0-9,包括 _(下划线)字符。”

测试设置将是:

const allowedCharacters = 'abc_123';
const unallowedCharacters = '*&^#';

const regex = /^\w+$/;
const regexString = "/^\w+$/"; // <- hence the string

// -------

console.log('--- regex without it coming from a string');

const regexObjectWithoutString = new RegExp(regex);

console.log('Should be abc_123: ', allowedCharacters.match(regex)); // ["abc_123"]
console.log('Should be true: ', regexObjectWithoutString.test(allowedCharacters)); // true
console.log('Should be false', regexObjectWithoutString.test(unallowedCharacters)); // false

// all good until now
// -------

console.log('--- this time regex from a string');

const regexObjectByString = new RegExp(regexString);

console.log('Should be abc_123: ', allowedCharacters.match(regexString)); // null
console.log('Should be true: ', regexObjectByString.test(allowedCharacters)); // false
console.log('Should be false', regexObjectByString.test(unallowedCharacters)); // false

小提琴:https ://jsfiddle.net/Spindle/cud3sLnh/

标签: javascriptregex

解决方案


您的示例字符串包含一些“有效字符”,因此/\w/表达式将始终找到匹配项。如果您希望正则表达式验证它仅包含匹配的字符,\w那么您的表达式应该是/^\w+$. 它从字符串的开头开始匹配,在结尾停止匹配,并且需要 1 个或多个\w字符。

我建议使用像https://regexr.com这样的工具,它可以在您尝试构建正则表达式时提供正则表达式的可视化。


推荐阅读