positive developer
positive developer

Reputation: 137

How can I Regex filename with exactly 1 underscores in javascript?

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?

Upvotes: 0

Views: 392

Answers (4)

Kiran Parajuli
Kiran Parajuli

Reputation: 1045

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

Upvotes: 1

tenbits
tenbits

Reputation: 8018

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

Upvotes: 0

Mina
Mina

Reputation: 17564

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')

Upvotes: 1

Mehmaam
Mehmaam

Reputation: 573

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

or

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

Upvotes: 0

Related Questions