Home > Software design >  How can I Regex filename with exactly 1 underscores in javascript?
How can I Regex filename with exactly 1 underscores in javascript?

Time:08-07

I need to match if filenames have exactly 1 underscores. For example:

Prof. Leonel Messi_300001.pdf    ->  true
Christiano Ronaldo_200031.xlsx    ->  true
Eden Hazard_3322.pdf       ->  true
John Terry.pdf    ->  false
100023.xlsx    ->  false
300022_Fernando Torres.pdf       ->  false

So the sample : name_id.extnames

Note : name is string and id is number

I try like this : [a-zA-Z\d] _[0-9\d]

Is my regex correct?

CodePudding user response:

As the filename will be name_id.extension, as name string or space [a-z\s] ? then underscore _, then the id is a number [0-9] ?, then the dot, as dot is a special character you need to scape it with backslash \., then the extension name with [a-z]

const checkFileName = (fileName) => {
  const result = /[a-z\s] ?_\d ?\.[a-z] /i.test(fileName);
  console.log(result);
  return result;
}

checkFileName('Prof. Leonel Messi_300001.pdf')
checkFileName('Christiano Ronaldo_200031.xlsx')
checkFileName('Eden Hazard_3322.pdf')
checkFileName('John Terry.pdf')
checkFileName('100023.xlsx')
checkFileName('300022_Fernando Torres.pdf')

CodePudding user response:

[a-zA-Z] _[0-9\d] 

or

[a-zA-Z] _[\d] 

CodePudding user response:

You should use ^...$ to match the line. Then just try to search a group before _ which doesn't have _, and the group after, without _.

^(?<before>[^_]*)_(?<after>[^_]*)\.\w $

https://regex101.com/r/ZrA7B1/1

CodePudding user response:

Regex

My try with separate groups for

  • name: Can contain anything. Last _ occurrence should be the end
  • id: Can contain only numbers. Last _ occurrence should be the start
  • ext: Before last .. Can only contain a-z and should be more than one character.
/^(?<name>. )\_(?<id>\d )\.(?<ext>[a-z] )/g

Regex 101 Demo

JS

const fileName = "Lionel Messi_300001.pdf"

const r = /^(?<name>. )\_(?<id>\d )\.(?<ext>[a-z] )/g

const fileNameMatch = r.test(fileName)

if (fileNameMatch) {
    r.lastIndex = 0
    console.log(r.exec(fileName).groups)
}

See CodePen

  • Related