Regex expression for file name with 2 underscores and 3 segments

和自甴很熟 提交于 2021-01-29 07:30:57

问题


I need a regex expression that will select files with particular file name format from the file list of properties files.
I need to select files with file names with following file format:

<app_name>_<app_version>_<environment>.properties
  • here <app_name> can be any alphanumeric with special character <A-Z/a-z/0-9/special char> like abc123 or app1-1
  • here <app_version> can be any alphanumeric with special character <A-Z/a-z/0-9/special char/float value> like abc or even float/integer/string 1.0 or 2 or abc1
  • here <environment> can be any alphanumeric with special character <A-Z/a-z/0-9/special char> like production or prod1

Together they are bind with 2 underscore as follows:-

<A-Z/a-z/0-9/special char>_<A-Z/a-z/0-9/special char/float value>_<A-Z/a-z/0-9/special char>.properties

The file name always contains 2 underscore _, and it can be any string between the underscores .
for examples, following are valid file names that can be selected:

app1_1.0_prod1.properties
app2_2_prod2.properties
app_vers1_prod.properties
app-1_vers1_prod-2.properties
asd_efg_eee.properties

It can be letter or number or special char or combination between them, between the underscore .
Please note that it can be only 2 underscore _ in the file name.
Anything other than 2 underscore _ is not a valid file name and will not be selected and the file name should always have these 3 sections separated by 2 underscore _
Following are invalid file name:

abc.properties
abc.123.efg.properties
as_1.efg.ddd.rr.properties
ee_rr.properties
_rr_.properties

I tried following regex:

[^_]*\\.[^_].properties  

but not working. Maybe this is wrong. I am not getting the clue of getting this. Please help me in creating this regex.
Thanks


回答1:


I believe /^[^_]+_[^_]+_[^_]+\.properties$/ should meet your requirements:

const tests = [
  'app1_1.0_prod1.properties',
  'app2_2_prod2.properties',
  'app_vers1_prod.properties',
  'asd_efg_eee.properties',
  'abc.properties',
  'abc.123.efg.properties',
  'as_1.efg.ddd.rr.properties',
  'ee_rr.properties',
  '_rr_.properties'
];

tests.forEach(test => { 
  console.log(test, /^[^_]+_[^_]+_[^_]+\.properties$/.test(test)); 
});

Alternatively, you could use /^([^_]+_){2}[^_]+\.properties$/

If you want to tighten down on the use of ., then I think you want

/^[^_.]+_([^_.]+|\d+(\.\d+)?)_[^_.]+\.properties$/



回答2:


This should work, since each section can include basically any character except an underscore: /[^_]*_[^_]*_[^_]\.properties/



来源:https://stackoverflow.com/questions/53750596/regex-expression-for-file-name-with-2-underscores-and-3-segments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!