Regular Expression Help

Meenal Gharat
Giga Guru

Hello Expert,

 

I'm trying to valid a string which starts with letters '_' and numbers in the transform map.

 

Can someone help me with regular expression.

 

I tried with "/^[ A-Za-z0-9_@./#&+-]*$/. "  yet no luck can someone please correct me.

 

Thank you!

 

Best Regards,

Meenal Gharat

4 REPLIES 4

Samaksh Wani
Giga Sage
Giga Sage

Hello @Meenal Gharat 

 

use this :-

 

 

^[0-9_]

 

Plz Mark my Solution as Accept and Give me thumbs up, if you find it helpful.

 

Regards,

Samaksh

Hemant Goldar
Mega Sage
Mega Sage

Hi @Meenal Gharat ,

You can also try in addition to Samaksh

/^[A-Za-z]*_[0-9]*$/

 

Thanks,

Hemant

Priyansh_98
Tera Guru

hi @Meenal Gharat ,

 

Hope you are doing well..!!!

for your regular expression requirement, you can use this regex in the transform map script.

from your question I understand is ..if the first letter of a string either starts with any alphabet [A-Z ( or )  a-z] or it starts with an underscore [  _  ] or the string starts with any number i.e. [0-9]..

then you can try with the below expression.

^[a-zA-Z0-9_][0-9a-zA-Z]*$

1st block of code will check the initial character of the string and 2nd block will check the remaining character of your string.

hope this may help you...

 

Good luck...

 

thomaskennedy
Tera Guru

You didn't tell us clearly what you are trying to discover about the string. It sounds like you want to test that it starts with a letter, and that everything after that is a letter, underscore or digit. But it's not very clear.

Regex is tricky and expensive, and only easy to read and understand for simple cases. And for simple cases you don't need it anyway. For example, if your requirement is "The string begins with an underscore,  every character after that is one of 0-9, and the string is 10 chars in length", you can do that as follows. Just comment what your code is checking for.

 

console.log( f("_041827492") );
console.log( f("_04139142i") );

function f(str){
	// Are all the following true?
	// str is ten chars in length
	// str begins with underscore
	// every subsequent char is a digit
	var result = str.length == 10 
		&& str.split('')[0] == '_'
		&& str.substring(1)
			.split('')
			.filter( function(e) { return ['0','1','2','3','4','5','6','7','8','9'].indexOf(e) == -1; } ) // remove everything not a digit
			.join('')
			.length == 0;
	return result;
}

C:\temp>node ex.js
true
false