javascript正则表达式问号(?)未检测到 [英] javascript Regex question mark (?) not detect

查看:121
本文介绍了javascript正则表达式问号(?)未检测到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我尝试用随机值创建一些正则表达式

Hi all I tried to create some regex with random value.

var data = "demo purpose?";  **OR**  var data = "demo purpose";
var sentence = "can I put these app as demo purpose?";
var re = new RegExp("\\b(" + data + ")\\b", "g");
console.log(sentence.match(re));   // output ["demo purpose"]

变量数据有两个不同的值演示用途?& 演示目的只带问号。两个控制台都是相同的请任何一个给我提示在这种情况下我应该做什么。

In variable data have two different value demo purpose? & demo purpose with only question mark. Both console out are same please any one Give me hint what should i do in these case.

-
谢谢

- Thank you

推荐答案

你需要逃避(即写 \\?)或它将被解释为正则表达式中的量词

you need to escape ? (i.e. write \\?) or else it would be interpreted as a quantifier in regex.

此外, \\\\ 并不是必需的,因为它试图匹配非空白字符,其中在演示目的后面没有任何内容?所以 sentence.match(新的RegExp(\\b(演示目的)\\?) \\b,g))将返回null。

Furthermore, the \\b is not really necessary because it tries to match a non blank char in which case there is nothing behind demo purpose? so sentence.match(new RegExp("\\b(demo purpose\\?)\\b", "g")) would return null.

如果您想要随机性,请使用的Math.random 。创建一个数组并获得一个随机整数或0或1(带有 Math.floor )作为索引。

If you want randomness, use Math.random. Make an array and get an random integer or 0 or 1 (with Math.floor) as the index.

这篇关于javascript正则表达式问号(?)未检测到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆