Regular expression for separating words by uppercase letters and numbers
I was wondering if anyone might know what the regular expression would be to turn this:
West4thStreet
into this:
West 4th Street
I'm going t开发者_如何转开发o add the spaces to the string in Objective-C.
Thanks!
I don't know exactly where you want to put in spaces, but try something like [a-z.-][^a-z .-]
and then put a space between the two characters in each match.
Something like this perl regex substitution would put a space before each group of capital letters or numbers. (You'd want to trim space before the string in this case also.) I assume you don't want it to break up eg: 45thStreet to 4 5th Street
Letters I'm less certain of.
s/([A-Z]+|[0-9]+)/ \1/g
I created a pattern to not match the beginning of the line for my personal amusement:
s/([^\^])([A-Z]+|[0-9]+)/\1 \2/g
This should work, if all your strings truly match the format of your example:
([A-Z][a-z]+)(\d+[a-z]+)([A-Z][a-z]+)
You can then separate the groups with spaces.
Another option would be to not use RegExKit and use code to loop through each character in the string and insert a space after each capital letter or after first decimal..
NSMutableString *myText2 = [[NSMutableString alloc] initWithString:@"The1stTest"];
bool isNumber=false;
for(int x=myText2.length-1;x>1;x--)
{
bool isUpperCase = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[myText2 characterAtIndex:x]];
bool isLowerCase = [[NSCharacterSet lowercaseLetterCharacterSet] characterIsMember:[myText2 characterAtIndex:x]];
if([[NSCharacterSet decimalDigitCharacterSet] characterIsMember:[myText2 characterAtIndex:x]])
isNumber = true;
if((isUpperCase || isLowerCase) && isNumber)
{
[myText2 insertString:@" " atIndex:x+1];
isNumber=false;
}
if(isUpperCase)
[myText2 insertString:@" " atIndex:x];
}
NSLog(@"%@",myText2); // Output: "The 1st Test"
精彩评论