andrej
andrej

Reputation: 331

Finding the string or substring within nth occurrence in a line

I would like to find the third occurrence of string inside quotes in order to replace this string or part of this string. This is a typical line I have to deal with:

"/activities/absenceactivity/lang/#LANG_ID#/prop_dialog.php";"BA2_PD_SCR";"Opis dogodka";"Event description";"Descrição do Evento";"ÐÐ¿Ð¸Ñ Ð¿Ð¾Ð´ÑÑ";"";"č®vykio aprašymas";"Descripción del evento";"";

I know that "([^"]*)" shows every occurrence of text and quotes but I would like to get just the third one, in this example "Opis dogodka" in order to perform Search & Replace in Sublime Text.

Problem is to find the third occurrence of string within the quotes, replace it entirely or just partially and make sure that the Regex provides also a solution for an empty

""

strings.

Thank you.

Upvotes: 3

Views: 1552

Answers (2)

dawg
dawg

Reputation: 103734

You can use {} pattern repetition:

/(?:"([^"]*)";){3}/   # first match group will be 'Opis dogodka'

Demo

Or, use a global type match and then take the third match. This might require logic such as slicing or looping:

/"([^"]*)";/g

Demo 2

Or, just manually put in the first two patterns to skip:

 /^"[^"]*";"[^"]*";("[^"]*";)/

Demo 3

Or combine repetition to skip the first n-1 then capture the nth match:

/^(?:"[^"]*";){2}("[^"]*";)/

Demo 4

Upvotes: 0

CoreyJJohnson
CoreyJJohnson

Reputation: 126

I'm sure there are ways to simplify this further, but if you're ok with brute force:

Sublime command:

 Find: "[^"]*";"[^"]*";"([^"]*)".*
 Replace: $1

NP++:

 Find what: "([^"]*)";"([^"]*)";"([^"]*)".*
 Replace with: $3

sed:

 sed 's/"\([^"]*\)";"\([^"]*\)";"\([^"]*\)".*/\3/'

Upvotes: 1

Related Questions