已要求我编写一个程序来验证字符串是否采用以下格式:
"<number><number><number><number><-><number><number><number><space><capitalized word/sentence>"
在满足要求时返回#t,在不满足要求时返回#f。
我尝试使用以下代码
(define (verify codpos)
(cond ((string<=? (substring codpos 0 4) "9999")
(string=? (substring codpos 4 5) "-")
(string<=? (substring codpos 5 8) "999")
(string=? (substring codpos 8 9) " ")
(string>? (substring codpos 9 (string-length codpos)) "9")
(string<? (substring codpos 9 (string-length codpos)) "a") #t)
(else #f)))
无论是否满足条件,它都表示#t。 我将不胜感激。我最近才刚开始编程,所以我不能像这样简单地练习。
答案 0 :(得分:0)
您可以使用正则表达式来实现此目的:
#lang racket
(define (verify-rexpr s)
(regexp-match? #px"^\\d{4}-\\d{3} (\\p{Lu}|\\s)*$" s))
(module+ test
(require rackunit)
; --
(check-true (verify-rexpr "1234-321 "))
(check-false (verify-rexpr "1234-0s1 "))
(check-true (verify-rexpr "9999-999 WORD"))
(check-false (verify-rexpr "1234-321 word"))
(check-true (verify-rexpr "1234-321 ALL CAPS SENTENCE"))
(check-false (verify-rexpr "1234-321 Not ALL CAPS SENTENCE")))
答案 1 :(得分:0)
我不理解大写单词/句子的意思是“带句子的大写单词”或“大写单词或句子”或“第一个字符串大写的句子”或“第一个字符串大写且长度可以是一个”。 “带有符号的句子”或“不允许其他符号”。
如果您想要这个“ 1234-123,这与符号和数字123相同。”
#lang racket
(define (varify str)
(and (>= (string-length str) 10)
(number? (string->number (substring str 0 4)))
(string=? (substring str 4 5) "-")
(number? (string->number (substring str 5 8)))
(string=? (substring str 8 9) " ")
(not (string=? (string-upcase (substring str 9 10))
(string-downcase (substring str 9 10))))
(string=? (string-upcase (substring str 9))
(substring str 9))))
(varify "1234-123 THIS IS SENSTANCE WITH SYMBOL - @AND NUMBER123.") ; #true
(varify "1234-123 T") ; #true
(varify "1234-123 ") ; #false
(varify "1234-123 !HIS IS ENSTANCE WITH SYMBOL - @AND NUMBER123.") ; #false
(varify "1234-123 HIS IS SENSTANCE WITH SYMBOL - @AND NUMBER123.") ; #false
(varify "1234-123 tHIS IS SENSTANCE WITH SYMBOL - @AND NUMBER123.") ; #false
(varify "1234-12a THIS IS SENSTANCE WITH SYMBOL - @AND NUMBER123.") ; #false