Home > Software design >  How can I capture a specific char inside specific strings with regex?
How can I capture a specific char inside specific strings with regex?

Time:12-14

I want to replace all the dots -that are inside specific strings- by underscores. In my case, I'm using i18n (for translations) inside my application, and the keys are called using '$t(key)'. Key can be like that :

key = 'translationKey'
key = 'translationKey.subkey.subSubkey'
key = 'translationKey.subkey.one'
key = 'translationKey.subkey.zero'
key = 'translationKey.subkey.others'

In the $t context: I want to transform the dots (.) that are not followed by one or zero or others into underscore (_). If I have those inputs :

foo.toto.anything
$t('translationKey')
$t('translationKey.subkey.subSubkey')
$t('translationKey.subkey.one')
$t('translationKey.subkey.zero')
$t('translationKey.subkey.others')

Then the output will be :

foo.toto.anything
$t('translationKey')
$t('translationKey_subkey_subSubkey')
$t('translationKey_subkey.one')
$t('translationKey_subkey.zero')
$t('translationKey_subkey.others')

I'd like to use Vscode regex search to capture those dots and to replace them (if possible).

I only managed to get all the strings where the target dots are, but I can't reach only the dots. Here's the the regex I have atm: (\$|\.)t?t(c|p)?('(\w \.?)*')

Thank you

CodePudding user response:

The following regular expression should work: it matches all the dots not followed by "one", "others", and "zero"

(?<=\$t\('[^'] )\.(?!one|others|zero)

You can test it online here

https://regex101.com/r/84Jil1/1

CodePudding user response:

You can use

(?<=\$t\('[^']*)\.(?!(?:one|zero|others)')(?=[^']*'\))

See the regex demo. Details:

  • (?<=\$t\('[^']*) - a positive lookbehind that requires $t(' and then any zero or more chars other than ' immediately to the left of the current location
  • \. - a dot
  • (?!(?:one|zero|others)') - a negative lookahead that fails the match if there are one', zero', or others' immediately to the right of the current location
  • (?=[^']*'\)) - a positive lookahead that requires zero or more chars other than ' and then ').
  • Related