简体   繁体   English

将特定的正则表达式模式与我的字符串匹配

[英]matching a specific regex pattern with my string

Hi I would like my regex pattern to match a character with a pattern of 0-9 and multiply and add operator. 嗨,我想让我的正则表达式模式将一个字符与一个0-9模式匹配,并乘以加运算符。 So far this is what I have done. 到目前为止,这是我所做的。

var regexPattern = /\d\+\*/;

function matchPattern( regexPattern, mycharacter ) {
    if ( mycharacter.match( regexPattern ) ) {
        console.log( 'true' );
    } else {
        console.log( 'false' );
    }
}

matchPattern( regexPattern, '+' );

the problem is when I pass the pattern like a number or a '+' or '*' sign it returns false instead. 问题是当我通过数字或“ +”或“ *”符号之类的模式时,它返回false。 What am I doing wrong? 我究竟做错了什么?

Change this line: 更改此行:

var regexPattern = [/\d\+\*/];

To this: 对此:

var regexPattern = /[\d\+\*]/;

Or, noting that you don't need to escape + or * when used within [] : 或者,注意在[]使用时,您无需转义+*

var regexPattern = /[\d+*]/;

You were creating an array containing a single element that is a regex. 您正在创建一个包含单个元素(即正则表达式)的数组。 What you want is a regex that uses the [] as part of its pattern. 您想要的是使用[]作为其模式一部分的正则表达式。

The pattern [\\d+*] will match a digit ( \\d ) or a plus sign ( + ) or an asterisk ( * ). 模式[\\d+*]将匹配数字( \\d )或加号( + )或星号( * )。

UPDATE for your edit: the pattern /\\d\\+\\*/ that you have will match a digit that is followed immediately by a plus sign that is followed by an asterisk. 编辑的更新:具有的模式/\\d\\+\\*/将匹配一个数字,该数字后面紧跟一个加号,后跟一个星号。 See above for the pattern you need. 请参阅上面的所需模式。

You need to put the square brackets inside the regex: /[\\d\\+\\*]/ this means that it will match any of the characters in the square brackets. 您需要将方括号放在正则表达式内: /[\\d\\+\\*]/这意味着它将与方括号中的任何字符匹配。

To match more than just one character, you'll need to put a + or * on the end: /[\\d\\+\\*]+/ to tell it to keep matching any number of digits, asterisks and plus signs. 要匹配多个字符,您需要在末尾加一个+*/[\\d\\+\\*]+/告诉它保持匹配任意数量的数字,星号和加号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM