Regular Expression practices in iOS development (1)
Requirement Abstraction:
Now there is a string
{"State": 200, "error": "Logon successful! "," Json ": {" auid ":" 402888f54c12441e014c1246bdf90003 "}}
Now we need to extract the content string after the auid, that is402888f54c12441e014c1246bdf90003
Analysis:
Before learning regular expressions, I use the following methods:
Convert the data into a dictionary in Json format and obtain the key.
If you want to obtain the content corresponding to the auid, you can use either of the following methods:
1. Convert json into a dictionary twice.
2. One dictionary + one string Truncation
However, both methods are cumbersome, so I thought of the string-processing method-regular expressions.
Steps:
1. Copy the original string to the regular expression tool (currently many online regular expression testing tools, I use RegExRX)
2. Test Matching
3. iOS code implementation
Note: although regular expressions are generic, the processing of each language is different. For example, in the expression just now, in iOS, \ d must be followed by escape characters \
The final code implementation is as follows:
// Regex // 1. create a regular expression object and specify the regular expression NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern: @ "[\ d \ w] {10,}" options: 0 error: nil]; // 2. obtain the range NSTextCheckingResult * match = [regex firstMatchInString: string options: 0 range: NSMakeRange (0, [string length])]; // 3. truncates a specific string if (match) {NSString * result = [string substringWithRange: match. range]; DDLogVerbose (@ "% @", result); // storage to preference settings [[NSUserDefaults standardUserDefaults] setObject: result forKey: @ "audi"];}
Conclusion:
This is just a simple match, and I have communicated with the server, knowing what the data format I want must be. all work should begin with demand. it is neither necessary nor comprehensive.