javascript - 如何在 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
解决方案
您的示例字符串包含一些“有效字符”,因此/\w/
表达式将始终找到匹配项。如果您希望正则表达式验证它仅包含匹配的字符,\w
那么您的表达式应该是/^\w+$
. 它从字符串的开头开始匹配,在结尾停止匹配,并且需要 1 个或多个\w
字符。
我建议使用像https://regexr.com这样的工具,它可以在您尝试构建正则表达式时提供正则表达式的可视化。
推荐阅读
- azure - 将新块上传到现有 Azure BlockBlob 时,块 ID 的最大长度是多少
- swiftui - 如何在 SwiftUI 中使 ViewModel 实例处于活动状态?
- flutter - 未处理的异常:状态不佳:调用关闭后无法添加新事件?
- android - 从 APK 运行时不显示图像
- nsis - 如何使用 NSIS 在卸载期间保存日志
- python - 使用 cmaps 进行散点图
- c# - win2D CanvasControl DrawImage() 通过错误“值不在预期范围内”?
- r - 如何使用geom将三个汇总数据点添加到ggplot而不必具有相同的数据大小?
- python - 如何引用在函数中初始化的列表?(Python)
- docker - 理解 docker create 命令行参数