How to write a regular expression to find all strings in an XCode project
Asked Answered
P

2

7

I need to find all the strings in my XCode project. I know that I can use grep and regex to accomplish this, but am well versed in neither.

The pattern I want to find is anything on one line that starts with '@"' and ends with '"'. I might throw in a minimum of 5 or so characters in between, also.

So for instance, if I searched through the following code:

NSArray *array = @[@"this is the first", @"this is the second"];
for (NSString* thisString in array)
{
    NSLog(@"%@", thisString);
}

Only "this is the first" and "this is the second" would be hits. Am I on the right track with using regex, or is there another technique that would be more suitable for this?

Thanks!

Playful answered 10/10, 2014 at 3:54 Comment(3)
@"%@" is also a string.Crushing
@"([^"]*)" regex101.com/r/xT7yD8/4Reichel
Oops - I'm saying that @"%@" wouldn't hit because it doesn't hit a minimum length requirement, didn't make that clearPlayful
M
23

Regex is fine for these sorts of searches. Here are a few quick 'n' dirty alternatives:

  • @".*?" - will find any occurrences including the quotes.
  • @".{5,}?" - does the same, but minimum five characters.
  • (?<=@").*?(?=") - if you want to exclude the quotes

These won't handle escaped quotation marks within the string, nor strings that spread across multiple lines (notably when the subsequent lines omit the leading @). It may also match occurrences in comments (not just code). It may also have problems if you have mismatched quotes (e.g. in your code comments).

If you're just quickly searching for strings, these regex strings might help. If you're trying to automate some replacement, some greater care is called for.

Miscible answered 10/10, 2014 at 4:33 Comment(1)
For Swift, remove the @ symbol from the regex.Brahmani
D
10

As of writing this using Xcode 12.5 you can simply enter an Any pattern in between two " in the search bar by clicking the magnifying glass. ⤵︎

enter image description here

Dyaus answered 18/7, 2021 at 22:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.