Anon30
Anon30

Reputation: 606

Regex - Find and replace single quotes between quotes

I have company array where lots of company name (array key) contains Single quotes.
Just wanted to escape Single quotes character in between the Starting & Ending single quotes in array key.

regex:

('[^']*)'s([^']*')

Samples:

'BJs Wholesale Club' => 'A',
'BJ's Wholesale Club' => 'A',
'Dillard's' => 'A',
'Divi's Labs' => 'A',
'Divis Labs' => 'A',
'ESKAY K 'N' (PVT) LTD' => 'B',
'Nahar Ind'l Enterprises' => 'A',
'Toys 'R' Us' => 'A',
'ToysR Us' => 'A',

Required Output:

'BJs Wholesale Club' => 'A',
'BJ\'s Wholesale Club' => 'A',
'Dillard\'s' => 'A',
'Divi\'s Labs' => 'A',
'Divis Labs' => 'A',
'ESKAY K \'N\' (PVT) LTD' => 'B',
'Nahar Ind\'l Enterprises' => 'A',
'Toys \'R\' Us' => 'A',
'ToysR Us' => 'A',

My regex doesn't work for company contains other thant \'s or more than one single quote

Demo: https://regex101.com/r/23aBEI/2

Upvotes: 0

Views: 1234

Answers (3)

Aaron
Aaron

Reputation: 24812

This should match every single quote you want to escape :

(?<!^)'(?=.*' =>)

It works by selecting every single quote that isn't at the beginning of the line ((?<!^)) and is followed at some point by the ' => part ((?=.*' =>)) by using lookarounds.

Replacing all occurences by \\' in notepad++ gives the following result :

'BJs Wholesale Club' => 'A',
'BJ\'s Wholesale Club' => 'A',
'Dillard\'s' => 'A',
'Divi\'s Labs' => 'A',
'Divis Labs' => 'A',
'ESKAY K \'N\' (PVT) LTD' => 'B',
'Nahar Ind\'l Enterprises' => 'A',
'Toys \'R\' Us' => 'A',
'ToysR Us' => 'A',

Upvotes: 2

Whothehellisthat
Whothehellisthat

Reputation: 2152

As Notepad++ supports PCRE (which allows us to use lookbehind), and it also supports multi-line, we can do it using the following:

Vairable lookbehind: (?<!^|=> )'(?! =>|,$)

Without vairable lookbehind: (?<!^)(?<!=> )'(?! =>)(?!,$)

Flags: multi-line. Replace with: \\'

Upvotes: 1

dquijada
dquijada

Reputation: 1699

This regex matches the whole company names (using the greedyness of the + operator).

'([a-zA-Z0-9\(\)' ]+)'

If the original string also contains the "=> 'A'" and you don't want to parse that, you can use this:

^'([a-zA-Z0-9\(\)' ]+)'

Note: you will need to activate the m flag to make this one work

In group 1 you will have your company name

Upvotes: 0

Related Questions