Regular Expression extract first three characters from a string

Any programming language should have a better solution than using a regular expression (namely some kind of substring function or a slice function for strings). However, this can of course be done with regular expressions (in case you want to use it with a tool like a text editor). You can use anchors to indicate the beginning or end of the string.

^.{0,3}
.{0,3}$

This matches up to 3 characters of a string (as many as possible). I added the “0 to 3” semantics instead of “exactly 3”, so that this would work on shorter strings, too.

Note that . generally matches any character except linebreaks. There is usually an s or singleline option that changes this behavior, but an alternative without option-setting is this, (which really matches any 3 characters):

^[\s\S]{0,3}
[\s\S]{0,3}$

But as I said, I strongly recommend against this approach if you want to use this in some code that provides other string manipulation functions. Plus, you should really dig into a tutorial.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)