What will be the best regex Expression for censoring email? - javascript

Hello I am stuck on a problem for censoring email in a specific format, but I am not getting how to do that, please help me!
Email : exampleEmail#example.com
Required : e***********#e******.com
Help me getting this in javascript,
Current code I am using to censor :
const email = exampleEmail#example.com;
const regex = /(?<!^).(?!$)/g;
const censoredEmail = email.replace(regex, '*');
Output: e**********************m
Please help me getting e***********#e******.com

You can use
const email = 'exampleEmail#example.com';
const regex = /(^.|#[^#](?=[^#]*$)|\.[^.]+$)|./g;
const censoredEmail = email.replace(regex, (x, y) => y || '*');
console.log(censoredEmail );
// => e***********#e******.com
Details:
( - start of Group 1:
^.| - start of string and any one char, or
#[^#](?=[^#]*$)| - a # and any one char other than # that are followed with any chars other than # till end of string, or
\.[^.]+$ - a . and then any one or more chars other than . till end of string
) - end of group
| - or
. - any one char.
The (x, y) => y || '*' replacement means the matches are replaced with Group 1 value if it matched (participated in the match) or with *.

If there should be a single # present in the string, you can capture all the parts of the string and do the replacement on the specific groups.
^ Start of string
([^\s#]) Capture the first char other than a whitespace char or # that should be unmodified
([^\s#]*) Capture optional repetitions of the same
# Match literally
([^\s#]) Capture the first char other than a whitespace char or # after it that should be unmodified
([^\s#]*) Capture optional repetitions of the same
(\.[^\s.#]+) Capture a dot and 1+ other chars than a dot, # or whitespace char that should be unmodified
$ End of string
Regex demo
In the replacement use all 5 capture groups, where you replace group 2 and 4 with *.
const regex = /^([^\s#])([^\s#]*)#([^\s#])([^\s#]*)(\.[^\s.#]+)$/;
[
"exampleEmail#example.com",
"test"
].forEach(email =>
console.log(
email.replace(regex, (_, g1, g2, g3, g4, g5) =>
`${g1}${"*".repeat(g2.length)}#${g3}${"*".repeat(g4.length)}${g5}`)
)
);

Related

Regex to capture all vars between delimiters

How do I capture all 1, 2 and 3 in not |1|2|3|
My regex \|(.*?)\| skips 2.
const re = /\|(.*?)\|/gi;
const text = 'not |1|2|3|'
console.log(text.match(re).map(m => m[1]));
You can use
const re = /\|([^|]*)(?=\|)/g;
const text = 'not |123|2456|37890|'
console.log(Array.from(text.matchAll(re), m => m[1]));
Details:
\| - a | char
([^|]*) - Group 1: zero or more chars other than |
(?=\|) - a positive lookahead that matches a location that is immediately followed with |.
If you do not care about matching the | on the right, you can remove the lookahead.
If you also need to match till the end of string when the trailing | is missing, you can use /\|([^|]*)(?=\||$)/g.

Struggling with RegEx validation and formating for specfici ID format

I have couple specific string formatting i want to achieve for different entities:
Entity 1: 1111-abcd-1111 or 1111-abcd-111111
Entity 2: [10 any symbol or letter(all cap) or number]-[3 letters]
Entity 3: [3 letters all cap]-[3 any]-[5 number]
Not sure if Regex is best approach, because i also want to use this as validator when user starts typing the char's it will check against that Entity selected and then against it's RegEx
Here is a regex with some input strings:
const strings = [
'1111-abcd-1111', // match
'1111-abcd-111111', // match
'1111-abcd-1111111', // no match
'ABCS#!%!3!-ABC', // match
'ABCS#!%!3!-ABCD', // nomatch
'ABC-#A3-12345', // match
'ABC-#A3-1234' // no match
];
const re = /^([0-9]{4}-[a-z]{4}-[0-9]{4,6}|.{10}-[A-Za-z]{3}|[A-Z]{3}-.{3}-[0-9]{5})$/;
strings.forEach(str => {
console.log(str + ' => ' + re.test(str));
});
Result:
1111-abcd-1111 => true
1111-abcd-111111 => true
1111-abcd-1111111 => false
ABCS#!%!3!-ABC => true
ABCS#!%!3!-ABCD => false
ABC-#A3-12345 => true
ABC-#A3-1234 => false
Explanation of regex:
^ - anchor text at beginning, e.g. what follows must be at the beginning of the string
( - group start
[0-9]{4}-[a-z]{4}-[0-9]{4,6} - 4 digits, -, 4 lowercase letters, -, 4-6 digits
| - logical OR
.{10}-[A-Za-z]{3} - any 10 chars, -, 3 letters
| - logical OR
[A-Z]{3}-.{3}-[0-9]{5} - 3 uppercase letters, -, any 3 chars, -, 5 digits
) - group end
$ - anchor at end of string
Your definition is not clear; you can tweak the regex as needed.

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?
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')
[a-zA-Z]+_[0-9\d]+
or
[a-zA-Z]+_[\d]+
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
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

How do I replace the last character of the selected regex?

I want this string {Rotation:[45f,90f],lvl:10s} to turn into {Rotation:[45,90],lvl:10}.
I've tried this:
const bar = `{Rotation:[45f,90f],lvl:10s}`
const regex = /(\d)\w+/g
console.log(bar.replace(regex, '$&'.substring(0, -1)))
I've also tried to just select the letter at the end using $ but I can't seem to get it right.
You can use
bar.replace(/(\d+)[a-z]\b/gi, '$1')
See the regex demo.
Here,
(\d+) - captures one or more digits into Group 1
[a-z] - matches any letter
\b - at the word boundary, ie. at the end of the word
gi - all occurrences, case insensitive
The replacement is Group 1 value, $1.
See the JavaScript demo:
const bar = `{Rotation:[45f,90f],lvl:10s}`
const regex = /(\d+)[a-z]\b/gi
console.log(bar.replace(regex, '$1'))
Check this out :
const str = `{Rotation:[45f,90f],lvl:10s}`.split('');
const x = str.splice(str.length - 2, 1)
console.log(str.join(''));
You can use positive lookahead to match the closing brace, but not capture it. Then the single character can be replaced with a blank string.
const bar= '{Rotation:[45f,90f],lvl:10s}'
const regex = /.(?=})/g
console.log(bar.replace(regex, ''))
{Rotation:[45f,90f],lvl:10}
The following regex will match each group of one or more digits followed by f or s.
$1 represents the contents captured by the capture group (\d).
const bar = `{Rotation:[45f,90f],lvl:10s}`
const regex = /(\d+)[fs]/g
console.log(bar.replace(regex, '$1'))

Javascript regex assistance

I have the following javascript regex...
.replace("/^(a-zA-Z\-)/gi", '');
It isn't complete... in fact it's wrong. Essentially what I need to do is take a string like "XJ FC-X35 (1492)" and remove the () and it's contents and the whitespace before the parenthesis.
replace(/^(.*?)\s?\(([^)]+)\)$/gi, "$1$2")
Takes XJ FC-X35 (1492) and returns XJ FC-X351492.
Remove the $2 to turn XJ FC-X35 (1492) into XJ FC-X35, if that's what you wanted instead.
Long explanation
^ // From the start of the string
( // Capture a group ($1)
.*? // That contains 0 or more elements (non-greedy)
) // Finish group $1
\s? // Followed by 0 or 1 whitespace characters
\( // Followed by a "("
( // Capture a group ($2)
[ // That contains any characters in the following set
^) // Not a ")"
]+ // One or more times
) // Finish group $2
\)$ // Followed by a ")" followed by the end of the string.
Try this:
x = "XJ FC-X35 (1492)"
x.replace(/\s*\(.*?\)/,'');

Categories

Resources