全部。我想知道Emacs lisp是否具有内置功能来检查字符串是否完全由大写字符组成。这是我现在正在使用的:

(setq capital-letters (string-to-list "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))

(defun chars-are-capitalized (list-of-characters)
  "Returns true if every character in a list of characters is a capital
letter. As a special case, the empty list returns true."
  (cond
   ((equal list-of-characters nil) t)
   ((not (member (car list-of-characters) capital-letters)) nil)
   (t (chars-are-capitalized (cdr list-of-characters)))))

(defun string-is-capitalized (string)
  "Returns true if every character in a string is a capital letter. The
empty string returns true."
  (chars-are-capitalized (string-to-list string)))

它可以正常工作(尽管它基于我只会使用ASCII字符的假设),但是我想知道我是否缺少一些我应该知道的明显功能。

最佳答案

引用其他答案:

  • 使用upcase并不是一个好主意:它会分配一个新字符串,它不会发现该字符串是否包含非字母字符(似乎您要禁止这样做),并且它也适用于整数(Emacs用于整数)人物)。
  • 使用string-match更好-它解决了所有这些问题。如Trey所示,当case-fold-searchnil时,您需要这样做,否则Emacs会将其视为不区分大小写的搜索。但是string-match-p甚至更好,因为它避免更改匹配数据。 (Emacs在任何匹配后都会保留这些数据,如果您使用string-match,则将其覆盖,这可能会破坏使用您的函数的代码。)
  • 另一个问题是正则表达式本身。使用"^...$"意味着Emacs将寻找内容匹配的行-如果您的字符串包含换行符,则可能会返回假结果。您需要使用仅与字符串的开头和结尾匹配的反斜杠取消引用和反斜杠引用。

  • 因此,正确的版本是:
    (defun string-is-capitalized (str)
      (let ((case-fold-search nil))
        (string-match-p "\\`[A-Z]*\\'" str)))
    

    (顺便说一句,Emacs Lisp中通常的约定是对谓词使用-p,就像string-capitalized-p一样。)

    关于emacs - 检查字符串是否在Emacs lisp中全部大写?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2129840/

    10-12 00:32
    查看更多