Regex Easy
NPM package to easily create regex
Motivation
I needed to create big regex and found it difficult to maintain and debug. So I started to split it in sub parts but the code was difficult to read. So I created this little package to help create big regex easily. It permits to create a formatted json object with the same structure as the regex object.
Features
- Each regex object create a JSON object.
- Each regex object must have a name and regex.
- Each regex object can be a boolean, optional or multiple
- A boolean regex object IS optional
- Each generated JSON object contain two internal properties
- _coverage_percent is an indication of the percentage of the raw text that has succesfully passed throught the regex
- _raw_text is the raw text sent to the regex
Code Example
const regex_easy = require('@nico87lbs/regex_easy');
let raw = 'Dupont Martin H 0607080910 20/10/1967 Paris Dupont Martine W 4567876545 Dutrou 5678987656 5678765456 18/10/2020 Bordeaux';
let obj = {
name: 'people_list',
multiple: true,
regex: [{
name: 'name',
regex: [{
name: 'lastname',
regex: /([A-Za-z]+)\s+/
},
{
name: 'firstname',
optional: true,
regex: /([A-Za-z]+)\s+/
}],
},
{
name: 'is_a_man',
boolean: true,
regex: /(?<true>H)?(?<false>W)?\s+/,
},
{
name: 'phone_number',
multiple: true,
regex: /([0-9]{10})\s+/
},
{
name: 'birth',
optional: true,
regex: /(?<date>[0-9]{2}\/[0-9]{2}\/[0-9]{4})\s+(?<city>\w+)\s?/
}]
};
try {
let r = regex_constructor(raw, obj);
console.log(JSON.stringify(r));
}
catch(e) {
console.error(e)
}
This code result in:
{
"people_list":[{
"name":{
"lastname":"Dupont",
"firstname":"Martin"
},
"is_a_man":true,
"phone_number":["0607080910"],
"birth":{
"date":"20/10/1967",
"city":"Paris"
}
},{
"name":{
"lastname":"Dupont",
"firstname":"Martine"
},
"is_a_man":false,
"phone_number":["4567876545"]
},{
"name":{
"lastname":"Dutrou"
},
"phone_number":["5678987656","5678765456"],
"birth":{
"date":"18/10/2020",
"city":"Bordeaux"
}
}],
"_coverage_percentage":"100",
"_raw_text":"Dupont Martin H 0607080910 20/10/1967 Paris Dupont Martine W 4567876545 Dutrou 5678987656 5678765456 18/10/2020 Bordeaux"
}
The following error can be generated (example keeping the same regex object but with a different raw text):
let raw = 'Dupont Martin H 0607 20/10/1967 Paris Dupont Martine W 4567876545 Dutrou 5678987656 5678765456 18/10/2020 Bordeaux';
{
code: 'noMatch',
msg: 'there is no match ',
data: {
raw_text: '0607 20/10/1967 Paris Dupont Martine W 4567876545 Dutrou 5678987656 5678765456 18/10/2020 Bordeaux',
regex_obj: {
name: 'phone_number',
multiple: true,
regex: /([0-9]{10})\s+/
}
}
}
Installation
npm install --save @nico87lbs/regex_easy
Contribute
If you find a bug or wish some improvement you can post a message in the Issue Tracker.
MIT © Yourname