[英]how to check whether a string have stars followed by four digit number?
I have a random string which is getting from database. 我有一个从数据库获取的随机字符串。 A string might be any length.
字符串可以是任何长度。 I need to check whether a string should be in this pattern like
*******1234
. 我需要检查一个字符串是否应该像
*******1234
这样的模式。 A string can have any number of stars (*) with four digit number. 一个字符串可以包含任意数量的星号(*)和四位数字。 How do I check that?
我该如何检查?
To check if a string starts with asterisks and ends with 4 digits, use this regexp: 要检查字符串是否以星号开头并以4位数结尾,请使用此正则表达式:
const exp = new RegExp('^\\\\*+\\\\d{4}$'); console.log(exp.test('***1234')) // true; console.log(exp.test('***12345')) // false console.log(exp.test('****234')) // false console.log(exp.test('***d1234')) // false console.log(exp.test('a***1234')) // false
^
: start of string ^
:字符串的开头 \\*+
: match at least one asterisk \\*+
:匹配至少一个星号 \\d{4}
: match exactly 4 digits \\d{4}
:恰好匹配4位数 $
: end of string $
:字符串结束 You can try RegEx /^\\*{1,}\\d{4}/
. 您可以尝试RegEx
/^\\*{1,}\\d{4}/
。
Where 哪里
^
starts the matching at the beginning of the string ^
在字符串的开头开始匹配
\\*{1,}
matches the character *
literally between one and unlimited times, as many times as possible, giving back as needed (greedy) \\*{1,}
在字面上与字符*
匹配,在一次和无限次之间,尽可能多次,根据需要返回(贪婪)
\\d{4}
matches a digit (equal to [0-9]) exactly 4 times \\d{4}
恰好匹配一个数字(等于[0-9])4次
With RegExp.prototype.test()
: 使用
RegExp.prototype.test()
:
The
test()
method executes a search for a match between a regular expression and a specified string.test()
方法执行搜索正则表达式和指定字符串之间的匹配。 Returnstrue
orfalse
.返回
true
或false
。
function checkString(str){ return /^\\*{1,}\\d{4}/.test(str); } console.log(checkString('*******1234')); console.log(checkString('*******12')); console.log(checkString('34*******1234'));
You can perform the task with two ways, First with regular expression and other with below : 您可以通过两种方式执行任务:第一种是正则表达式,另一种是下面的:
var id = "ctl03_Tabs1";
var lastFive = id.substr(id.length - 5); // => "Tabs1"
var lastChar = id.substr(id.length - 1); // =>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.