Mirzhan Irkegulov
Mirzhan Irkegulov

Reputation: 18055

Check if a character (not string) is lowercase, uppercase, alphanumeric?

What is the idiomatic and most effecient way to check if a single character in Elisp is lowercase, uppercase, alphanumeric, digit, whitespace, or any other similar character category? For example Python has string methods like isdigit(), but converting a character (which is just a number) to a string in Elisp to check if it belongs to a certain case or category seems like a wrong approach:

(string-match-p "[[:lower:]]" (char-to-string ?a))

Upvotes: 2

Views: 1182

Answers (2)

Michael Allan
Michael Allan

Reputation: 3921

Use get-char-code-property to look up the Unicode general category of the character. A lower-case letter, for example, gives a value of "Ll":

(string= "Ll" (get-char-code-property ?a 'general-category))
     ⇒ t

An upper-case letter gives "Lu", and a decimal number "Nd". See the full list of values.

Upvotes: 4

sds
sds

Reputation: 60014

There is no standard way, but I think it is not hard to roll your own:

(defun wordp (c) (= ?w (char-syntax c)))
(defun lowercasep (c) (and (wordp c) (= c (downcase c))))
(defun uppercasep (c) (and (wordp c) (= c (upcase c))))
(defun whitespacep (c) (= 32 (char-syntax c)))

See also cl-digit-char-p in cl-lib.el.

Upvotes: 4

Related Questions