0

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.

  1. new RegExp('^[a-zA-Z0-9*]+$').test('test') ---Valid
  2. new RegExp('^[a-zA-Z0-9*]+$').test('test1234') --Valid
  3. new RegExp('^[a-zA-Z0-9*]+$').test('test@#_')--Invalid
  4. new RegExp('^[a-zA-Z0-9*]+$').test('****1234') --Valid
  5. new RegExp('^[a-zA-Z0-9*]+$').test('*tes**1234') --Valid
  6. 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

2
  • Your question is ambiguous regarding asterisks between the first and the last four positions. The examples don't make that clear either. What about *1*2345, for example? Commented Feb 13, 2023 at 16:18
  • Yes, it is valid. Asterisk is allowed except for last 4 digits. And I have update that case with example Commented Feb 13, 2023 at 16:21

1 Answer 1

2

You can use this regex to allow only alphanumeric chars and asterisk, but no asterisk at the last 4 char positions:

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);
});

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. In my case this worked for me. That was a clear and concise explanation. Upvoting this since it passed all my test scenarios

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.