用于检测android字符串资源的可注入部分的正则表达式模式

时间:2015-06-05 13:00:46

标签: java regex

Android localisable字符串资源存储在xml中。这不是真正相关的,但有时会有一些特殊的模式,如:

%n$t - n总是整数,t可能是s,d或f(基本上是单个字母字母)。以下示例:

%1$s
%5$s
%45$s
%2$f
%3$d
%11$d

我可以用什么正则表达式替换另一个的匹配部分?

我的预期结果将是:

{s}
{s}
{s}
{n}
{n}
{n}

2 个答案:

答案 0 :(得分:4)

我想你想要这样的东西,

"%\\d+\\$[sdf]"

答案 1 :(得分:0)

看到您的更新后,您想要替换整个匹配字符串

    #pragma mark NSURLConnection Delegate Methods

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
        _dataDictionary = [NSMutableDictionary new];
        _theReceivedData = [NSMutableData new];

        [_theReceivedData setLength:0];
        // add object
        [_dataDictionary setObject:_theReceivedData forKey:[connection description]];
    }

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

        NSMutableData *imageData = _dataDictionary[ [connection description] ];
        [imageData appendData:data];
        if([connection description]!=nil && imageData!=nil)
        {
            [_dataDictionary setObject:imageData forKey:[connection description]];
        }
    }

    - (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                      willCacheResponse:(NSCachedURLResponse*)cachedResponse {
        // Return nil to indicate not necessary to store a cached response for this connection
        return nil;
    }

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        // The request is complete and data has been received
        // You can parse the stuff in your instance variable now

        NSData *imageData = _dataDictionary[ [connection description] ];

if(imageData!=nil)
    {
        NSLog(@"%@",imageData);

用法:

"%\\d+\\$[a-zA-Z]"

结果:

public static void main(String[] args) throws Exception {
    String[] strings = {
        "Test %1$s",
        "Test %5$s",
        "Test %45$s",
        "Test %2$f",
        "Test %3$d",
        "Test %11$d"
    };

    for (String string : strings) {
        System.out.println(string.replaceFirst("%\\d+\\$[a-zA-Z]", "something"));
    }
}