문자열이 숫자로만 구성되어 있는지 어떻게 확인할 수 있습니까? 문자열에서 부분 문자열을 꺼내 숫자 부분 문자열인지 확인하고 싶습니다.
NSString *newString = [myString substringWithRange:NSMakeRange(2,3)];
답변
다음은 문자열을 숫자로 구문 분석하려는 제한된 정밀도에 의존하지 않는 한 가지 방법입니다.
NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
{
// newString consists only of the digits 0 through 9
}
+[NSCharacterSet decimalDigitCharacterSet]
및을 참조하십시오 -[NSString rangeOfCharacterFromSet:]
.
답변
NSNumberFormatter 클래스 의 numberFromString:
메서드를 사용하는 것이 좋습니다. 마치 숫자가 유효하지 않으면 nil을 반환합니다. 그렇지 않으면 NSNumber를 반환합니다.
NSNumberFormatter *nf = [[[NSNumberFormatter alloc] init] autorelease];
BOOL isDecimal = [nf numberFromString:newString] != nil;
답변
"^[0-9]+$"
다음 방법 으로 정규식, 패턴으로 유효성 검사-validateString:withPattern:
.
[self validateString:"12345" withPattern:"^[0-9]+$"];
- “123.123”이 고려되는 경우
- 패턴
"^[0-9]+(.{1}[0-9]+)?$"
- 패턴
- 정확히 4 자리 숫자 인 경우
"."
.- 패턴
"^[0-9]{4}$"
.
- 패턴
- 숫자가없는 경우
"."
이고 길이가 2 ~ 5 인 경우- 패턴
"^[0-9]{2,5}$"
.
- 패턴
- 빼기 기호 사용 :
"^-?\d+$"
정규식을 체크인 할 수 있습니다. 은 온라인 웹 사이트 .
도우미 기능은 다음과 같습니다.
// Validate the input string with the given pattern and
// return the result as a boolean
- (BOOL)validateString:(NSString *)string withPattern:(NSString *)pattern
{
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
NSAssert(regex, @"Unable to create regular expression");
NSRange textRange = NSMakeRange(0, string.length);
NSRange matchRange = [regex rangeOfFirstMatchInString:string options:NSMatchingReportProgress range:textRange];
BOOL didValidate = NO;
// Did we find a matching range
if (matchRange.location != NSNotFound)
didValidate = YES;
return didValidate;
}
Swift 3 버전 :
놀이터에서 테스트하십시오.
import UIKit
import Foundation
func validate(_ str: String, pattern: String) -> Bool {
if let range = str.range(of: pattern, options: .regularExpression) {
let result = str.substring(with: range)
print(result)
return true
}
return false
}
let a = validate("123", pattern: "^-?[0-9]+")
print(a)
답변
NSScanner를 만들고 단순히 문자열을 스캔 할 수 있습니다.
NSDecimal decimalValue;
NSScanner *sc = [NSScanner scannerWithString:newString];
[sc scanDecimal:&decimalValue];
BOOL isDecimal = [sc isAtEnd];
선택할 수있는 더 많은 방법은 NSScanner의 문서 를 확인하십시오 .
답변
주어진 문자열 내의 모든 문자가 숫자인지 확인하는 가장 쉬운 방법은 아마도 다음과 같습니다.
NSString *trimmedString = [newString stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
if([trimmedString length])
{
NSLog(@"some characters outside of the decimal character set found");
}
else
{
NSLog(@"all characters were in the decimal character set");
}
허용 가능한 문자를 완전히 제어하려면 다른 NSCharacterSet 팩토리 메소드 중 하나를 사용하십시오.
답변
이 원래 질문은 Objective-C에 관한 것이었지만 Swift가 발표되기 몇 년 전에 게시되었습니다. 따라서 Google에서 여기에 왔고 Swift를 사용하는 솔루션을 찾고 있다면 여기에 있습니다.
let testString = "12345"
let badCharacters = NSCharacterSet.decimalDigitCharacterSet().invertedSet
if testString.rangeOfCharacterFromSet(badCharacters) == nil {
print("Test string was a number")
} else {
print("Test string contained non-digit characters.")
}
답변
문자열에 숫자 만 있는지 확인해야하는 경우 Swift 3 솔루션 :
CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: myString))
