正则表达式匹配“但不是”

时间:2012-11-06 23:06:12

标签: iphone objective-c ios regex

如何构造一个与文字匹配的正则表达式“但前提是它不在转义斜杠前面,即\

我有一个NSMutableString str,在NSLog 上打印以下内容。字符串是从服务器在线接收的。

"Hi, check out \"this book \". Its cool"

我想更改它,以便在NSLog上打印以下内容

Hi, check out "this book ". Its cool

我最初使用的是“replaceOccurencesOfString”“\”和“”。但是它会执行以下操作:

Hi, check out \this book \. Its cool

所以,我总结说我需要上面的正则表达式只匹配“但不是”,然后只替换那些双引号。

感谢 MBH

4 个答案:

答案 0 :(得分:1)

[^\\]\"

[^ m]表示与m

不匹配

答案 1 :(得分:0)

不确定正则表达式,更简单的解决方案是,

NSString *str = @"\"Hi, check out \\\"this book \\\". Its cool\"";
NSLog(@"string before modification = %@", str);    
str = [str stringByReplacingOccurrencesOfString:@"\\\"" withString:@"#$%$#"];
str = [str stringByReplacingOccurrencesOfString:@"\"" withString:@""];
str = [str stringByReplacingOccurrencesOfString:@"#$%$#" withString:@"\\\""];//assuming that the chances of having '#$%$#' in your string is zero, or else use more complicated word
NSLog(@"string after modification = %@", str);

输出:

string before modification = "Hi, check out \"this book \". Its cool"
string after modification = Hi, check out \"this book \". Its cool

正则表达式:[^\"].*[^\"].,即Hi, check out \"this book \". Its cool

答案 2 :(得分:0)

不确定这可能会如何转化为iOS apis支持的内容,但是,如果它们支持锚定(我认为所有正则表达式引擎都应该),那么您将描述类似

的内容

(^ | [^ \])“

即匹配:

  1. 字符串^的开头或任何不符合的字符 \后跟:
  2. "字符
  3. 如果您想进行任何替换,您必须抓住正则表达式中的第一个(也是唯一的)组(即表达式的括号内部分组)并在替换中使用它。通常这个值标记为$ 1或\ 1或类似替换字符串中的值。

    如果正则表达式引擎基于PCRE,当然您可以将分组表达式置于后台,这样您就不需要在替换中捕获并保存捕获。

答案 3 :(得分:0)

看起来它是一个JSON字符串?也许在服务器上使用PHP中的json_encode()创建?您应该在iOS中使用正确的JSON解析器。不要使用正则表达式,因为你会遇到错误。

// fetch the data, eg this might return "Hi, check out \"this book \". Its cool"
NSData *data = [NSData dataWithContentsOfURL:@"http://example.com/foobar/"];

// decode the JSON string
NSError *error;
NSString *responseString = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

// check if it worked or not
if (!responseString || ![responseString isKindOfClass:[NSString class]]) {
   NSLog(@"failed to decode server response. error: %@", error);
   return;
}

// print it out
NSLog(@"decoded response: %@", responseString);

输出将是:

Hi, check out "this book ". Its cool

注意:JSON解码API接受NSData对象,而不是NSString对象。我假设你也有一个数据对象,并在某些时候将它转换为字符串...但如果你不是,你可以使用以下命令将NSString转换为NSData:

NSString *responseString = [NSJSONSerialization JSONObjectWithData:[myString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];

有关JSON的更多详细信息,请访问:

相关问题