• Post Reply Bookmark Topic Watch Topic
  • New Topic

test if a name is variable with regex  RSS feed

 
yotam laor
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I would like to test whether the first word in a line is is a valid var name (e.g sequence of letters, digits and "_", it may not start with a digit, if "_" is the first char it must be followed by a letter).
I tried this simple code:



"__c" is an illegal var name.
But it returns the string "_c", where it is supposed to return an empty matcher.

where am I wrong here?

 
Hauke Ingmar Schmidt
Rancher
Posts: 436
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A Matcher is created in any case. But you need to check the matches method afterwards, and that returns false for __c and true for _c.

What exactly do you mean by "it returns the stting _c"?
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your regex will match any underscore followed by either letters or numbers. Your sample variable name does contain such a sequence of characters, so it matches that. You need to tell it that the thing it matches must be proceeded and followed by an unmatched word boundary.

You'll also find that your regex doesn't quite work.

* It will only match sequences that start with an underscore.
* It will allow a number to follow an underscore.

(edited because I missed the +, its early here)
 
yotam laor
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks,

Think I got it,

Just added "[ ]*" at the beginning.

 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a specific symbol for a word boundary, I think its \w. That will match all whitespace (not just spaces). I can't remember if it also matches the start or end of a line too.

Adding that in won't solve the other issues though.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!