这应该不会太难,正则表达式是/\&\#x([0-9a-fA-F]+)\;/
.
将捕获的数字包含在字符串中后,您就可以使用NSScanner
.
int value = NSNotFound;
[[NSScanner scannerWithString:capturedHexString] scanHexInt:&value];
NSString *decimalString = [NSString stringWithFormat:@"%d", value];
希望有帮助。
澄清
我将把它作为一个简单的功能提取出来
static inline NSString *MyDecimalStringFromHexString(NSString *hexString)
{
unsigned value = NSNotFound;
[[NSScanner scannerWithString:hexString] scanHexInt:&value];
NSString *decimalString = nil;
if (value != NSNotFound)
decimalString = [NSString stringWithFormat:@"%d", value];
return decimalString;
}
把它们放在一起
这是一个单元测试,它使用正则表达式/\&\#x([0-9a-fA-F]+)\;/
、您链接的类别以及我创建的十六进制到十进制函数来执行您想要的替换。
- (void)testHexEntityToDecimalEntity
{
NSString *input = @"This 
 is ઼ test";
NSString *expected = @"This is ઼ test";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\&\\#x([0-9a-fA-F]+)\\;" options:0 error:nil];
NSString *actual = [regex stringByReplacingMatchesInString:input options:0 range:NSMakeRange(0, input.length) usingBlock:^NSString *(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange hexRange = [result rangeAtIndex:1];
NSString *hexString = [input substringWithRange:hexRange];
NSString *decimalString = MyDecimalStringFromHexString(hexString);
return [NSString stringWithFormat:@"&#%@;", decimalString];
}];
STAssertEqualObjects(actual, expected, nil);
}