Sinisterly
REGEX FOR VALID JAVASCRIPT VARIABLE IN 1ST CHARACTER - Printable Version

+- Sinisterly (https://sinister.ly)
+-- Forum: Coding (https://sinister.ly/Forum-Coding)
+--- Forum: Java, JVM, & JRE (https://sinister.ly/Forum-Java-JVM-JRE)
+--- Thread: REGEX FOR VALID JAVASCRIPT VARIABLE IN 1ST CHARACTER (/Thread-REGEX-FOR-VALID-JAVASCRIPT-VARIABLE-IN-1ST-CHARACTER)



REGEX FOR VALID JAVASCRIPT VARIABLE IN 1ST CHARACTER - FractalBomb - 04-06-2017

Why am I so stupid? I need to test one character.
Regex has scared me for so long, I really don't know what I'm doing.
I'm writing a parser, so I'm only testing one character at a time.
the block of code I'm working with "knows" it's about to work on a variable. (or expects to)
For the first character in that variable I need to determine if it's $, _ or abc(a letter).
Code:
if( /\w_$/g.test( _.getCurr() ) )
This, does not work. It doesn't match for $


RE: REGEX FOR VALID JAVASCRIPT VARIABLE IN 1ST CHARACTER - Inori - 04-11-2017

I'm a bit late here, but this doesn't work for a few reasons.

First, because "$" matches the end of the test string (or the line if you're using the multiline "m" modifier). To match the $ character literally, you need to escape it ("\$").
Second, you're not using character ranges. Your current pattern tries to match a letter, then an underscore, then the end of the string via $ instead of any of those.
Third, it's pretty inefficient. If you're testing the first character of a string, why not just do that and eliminate the unnecessary function call? Just use a caret at the beginning to match the start of a string (opposite of $).

Finally, you don't need the global modifier since you're not looking for multiple (or any) matches. A working (and more efficient) regex pattern is included below.
The $ doesn't need escaping because it's in the range, which treats all characters as literal.

Code:
/^[a-zA-Z_$]/.test(fullString)

I highly recommend regex 101 to anyone who uses regular expressions often. It's a great visual tester and has tons of resources and reference for learning. Hell, I still use it weekly. Regex is hard, but it's a valuable skill to have, don't get too discouraged.


RE: REGEX FOR VALID JAVASCRIPT VARIABLE IN 1ST CHARACTER - ProfessorChill - 04-17-2017

I tried this /([A-Z]_?\$?)+$/ig and it works for myself. I would recommend using the one above mine though being as I didn't really test mine that much o-O
Also I didn't read your question that heavily, too tired to read D:


RE: REGEX FOR VALID JAVASCRIPT VARIABLE IN 1ST CHARACTER - Shin - 04-17-2017

I'm not even going to test it, but thanks!
It looks very legit and I would recommend.
BTW, HOW LONG DID IT TAKE FOR YOU TO MAKE THIS?


RE: REGEX FOR VALID JAVASCRIPT VARIABLE IN 1ST CHARACTER - FractalBomb - 04-17-2017

I got my issue fixed. thanks