Reputation: 137
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
Reputation: 1045
My try with separate groups for
name
: Can contain anything. Last _
occurrence should be the endid
: Can contain only numbers. Last _
occurrence should be the startext
: Before last .
. Can only contain a-z
and should be more than one character./^(?<name>.+)\_(?<id>\d+)\.(?<ext>[a-z]+)/g
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
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
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