Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
Regular Expression question that include different letters

I am trying to figure out Regex that will only accept below strings.

  • 7 and 8 numbers: '1234567' and '12345678'

  • 7 and 8 numbers that start with T: 'T234567' and 'T2345678'

  • 7 and 8 numbers that start with D: 'D234567' and 'D2345678'

  • 7 and 8 numbers that start with TD: 'TD34567' and 'TD345678'

Regex I have is:

/^(T|[0-9]){1}(D|[0-9]){1}([0-9]){5,6}$/

but it's not passing my unit test for 'D234567' and 'D2345678'

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You could write the pattern as:

^(?:\d{7,8}|[TD]\d{6,7}|TD\d{5,6})$

Explanation

  • ^ Start of string
  • (?: Non capture group for the alternatives
    • \d{7,8} Match 7-8 digits
    • | Or
    • [TD]\d{6,7} Match either T or D and 6-7 digits
    • | Or
    • TD\d{5,6} Match TD and 5-6 digits
  • ) Close the non capture group
  • $ End of string

Regex demo.

about 4 years ago · Santiago Trujillo Report

0

const r = /^(?=.{7,8}$)T?D?\d+$/

is the simplest solution. Here's a breakdown of what happens:

import {lookAhead, maybe, sequence, suffix} from "compose-regexp"

const r = sequence(
  // start anchor
  /^/,
  // are there exactly 7 or 8 characters before the end?
  lookAhead(suffix([7,8], /./), /$/),
  // optionally match a 'T'
  maybe('T'),
  // optionally match a 'D'
  maybe('D'),
  // match numbers until the end
  suffix('+', /\d/),
  /$/
)

You can try it out here

With tests aplenty.

about 4 years ago · Santiago Trujillo Report

0

I actually figure it out right after posted this question. Simply added |D after T| so like this.

/^(T|D|[0-9]){1}(D|[0-9]){1}([0-9]){5,6}$/

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!