英文:
JavaScript Alphanumeric Regex and allow asterisk at the start of the string but do not allow asterisk at the last 4 digits of the string
问题
只允许在字符串开头出现星号(*),并且不允许星号出现在字符串的最后四位位置。
英文:
I have this regex ^[a-zA-Z0-9*]+$ for only allowing alphanumeric chars and allow Asterisk(*). But I would like allow asterisk only at the start of the string. But asterisk is not allowed at the last 4 digits of the string.
- new RegExp('^[a-zA-Z0-9*]+$').test('test') ---Valid
- new RegExp('^[a-zA-Z0-9*]+$').test('test1234') --Valid
- new RegExp('^[a-zA-Z0-9*]+$').test('test@#_')--Invalid
- new RegExp('^[a-zA-Z0-9*]+$').test('****1234') --Valid
- new RegExp('^[a-zA-Z0-9*]+$').test('*tes**1234') --Valid
- new RegExp('^[a-zA-Z0-9*]+$').test('test****') --Should be Invalid
"How would I allow Asterisk only at the start of the string?" But if the asterisk presents in any of the last 4 positions then it should be invalid
答案1
得分: 1
你可以使用这个正则表达式来只允许字母数字字符和星号,但不允许星号出现在字符串的最后4个位置:
const regex = /^(?:[a-z\d*]*[a-z\d]{4}|[a-z\d]{1,3})$/i;
[
'1',
'12',
'test',
'test1234',
'****1234',
'*tes**1234',
'*1*2345',
'test@#_',
'test****',
'test***5',
'test**4*',
'*3**'
].forEach(str => {
let result = regex.test(str);
console.log(str, '==>', result);
});
输出结果:
1 ==> true
12 ==> true
test ==> true
test1234 ==> true
****1234 ==> true
*tes**1234 ==> true
*1*2345 ==> true
test@#_ ==> false
test**** ==> false
test***5 ==> false
test**4* ==> false
*3** ==> false
正则表达式的解释:
^
-- 锚定在字符串的开头(?:
-- 开始非捕获组(用于逻辑“或”)[a-z\d*]*[a-z\d]{4}
-- 允许字母数字字符和星号,后面跟着4个字母数字字符
|
-- 逻辑“或”[a-z\d]{1,3}
-- 允许1到3个字母数字字符
)
-- 结束组$
-- 锚定在字符串的末尾
注意,使用/.../
比 new RegExp("...")
更容易阅读和更高效。只有在有变量输入时才需要使用正则表达式构造函数。
英文:
You can use this regex to allow only alphanumeric chars and asterisk, but no asterisk at the last 4 char positions:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const regex = /^(?:[a-z\d*]*[a-z\d]{4}|[a-z\d]{1,3})$/i;
[
'1',
'12',
'test',
'test1234',
'****1234',
'*tes**1234',
'*1*2345',
'test@#_',
'test****',
'test***5',
'test**4*',
'*3**'
].forEach(str => {
let result = regex.test(str);
console.log(str, '==>', result);
});
<!-- end snippet -->
Output:
1 ==> true
12 ==> true
test ==> true
test1234 ==> true
****1234 ==> true
*tes**1234 ==> true
*1*2345 ==> true
test@#_ ==> false
test**** ==> false
test***5 ==> false
test**4* ==> false
*3** ==> false
Explanation of regex:
^
-- anchor at start of string(?:
-- start non-capture group (for logical OR)[a-z\d*]*[a-z\d]{4}
-- allow alphanumeric chars and asterisk, followed by 4 alphanumeric chars
|
-- logical OR[a-z\d]{1,3}
-- allow 1 to 3 alphanumeric chars
)
-- close group$
-- anchor at end of string
Not that it is easier to read and more efficient to use /.../
instead of new RegExp("...")
. You need the regex constructor only if you have variable input.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论