Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regex for SPSS field input

Status
Not open for further replies.

BomberMan2K

Programmer
Sep 19, 2007
36
IL
Hi guys,
I'm trying to build this little nifty form to get field names for SPSS software. The catch is it can only start with an alphachar (a-zA-z), continue with alphanumeric chars (a-z, A-Z, 0-9, _ - underscope) and can end with only alphanumeric char (not with an underscope).

suppose "val" is my input, I'm trying this regex:
if (val.match(/^([a-zA-Z]{1,}?|[a-zA-Z][a-zA-Z0-9_]+[a-zA-Z0-9])$/))

It works fine, but doesn't validate for "h1" for example (though it should). for "h_1" it does...
What is wrong with my expression here? Why doesn't it validate for "h1"?

Thank you,
Roman.
 
Match 1st (alpha), 2nd through 5th (alphanum + _), 6th alpha

val = 'aad_3a_d2__a3'; // fails
val = 'aad_3a'; // pass
val = 'hh'; // pass
val = 'h1'; // pass

val.match(/^([a-zA-Z]{1}|[a-zA-Z][a-zA-Z0-9_]{1,4}[a-zA-Z0-9]$/);



Match 1st (alpha), 2nd through xth (alphanum + _), xth+1 alpha

val = 'aad_3a_d2__a3'; // pass
val = 'aad_3a'; // pass
val = 'h3asd3'; // pass
val = 'h1'; // pass

val.match(/^([a-zA-Z]{1}|[a-zA-Z][a-zA-Z0-9_]{1,}[a-zA-Z0-9])$/);

Darrell
 
Thanks Darrel,
But strangely enough - your regex doesn't work as well.

val = "h1" doesn't work. but "h11" does.

As I look at the regex it seems just fine... but still, something is wrong.

Would very appreciate more help :)


Roman.
 
Found the solution. Here it is: (seems to work 100%)

val.match(/^([a-zA-Z]{1,}|[a-zA-Z][a-zA-Z0-9_]{0,}[a-zA-Z0-9]{1,})$/)
 
[tt]/^[a-zA-Z][a-zA-Z0-9_].*[a-zA-Z0-9]$/[/tt]
Or, unlikely needed for field names, this.
[tt]/^[a-zA-Z][a-zA-Z0-9_][\s\S]*[a-zA-Z0-9]$/[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top