Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace "1Don't do that" with "_1Don_t_do_that"

Tags:

regex

xcode

I need to modify the keys of a key value file as follows:

"1Don't do that" = "some value"

to

"_1Don_t_do_that" = "some value"
  • prepend with underscore if string starts with a number
  • replace any non alphanumeric char with underscore
  • do not alter the value string

I can do it in several steps if necessary

I've tried things like \"\w+[^\w]\w+\" = but it doesn't account for multiple spaces and does not single or double quotes.

Any help is welcome.

like image 546
znat Avatar asked Jul 08 '13 21:07

znat


2 Answers

Assuming that none of your quotes are escaped, this should work:

(?:(?<=")(?=\d)|[^\w"])(?=[^"]*"\s*=)

This matches

  • either the position between " and a digit
  • or a non-alphanumeric character (except a quote),

but only if they are followed by a single quote and an equals sign.

See it live on regex101.

like image 143
Tim Pietzcker Avatar answered Oct 16 '22 10:10

Tim Pietzcker


I’m not sure what regex flavor Xcode uses, but as long as it supports positive lookahead (?=), this series of replacements should work:

  1. Prepend with underscore if string starts with a number
    • find: ^"(?=\d)
    • replace all: "_
  2. Replace any non alphanumeric char with underscore, making sure that the value string is after, not part of, what we're changing.
    • find: [^a-zA-Z0-9](?=[^"]*"\s*=\s*"[^"]*")
    • replace all: _

The second step assumes that quote characters never occur in the value string; tell me if you need to handle backslash-escaped quote characters.

like image 39
Rory O'Kane Avatar answered Oct 16 '22 12:10

Rory O'Kane