Replacing character between square brackets

A={'[ABC; DEF];[GHI; JKH];'; '[ZBC; YEF];[XHI; UKH];'}
I need to replace ";" only which are appearing within sqare brackets with "^"

 Respuesta aceptada

Stephen23
Stephen23 el 2 de Mzo. de 2020
Editada: Stephen23 el 2 de Mzo. de 2020
>> A = {'[ABC; DEF];[GHI; JKH];'; '[ZBC; YEF];[XHI; UKH];'}
A =
'[ABC; DEF];[GHI; JKH];'
'[ZBC; YEF];[XHI; UKH];'
>> B = regexprep(A,'(\[[^\]]+);([^\]]+\])','$1^$2')
B =
'[ABC^ DEF];[GHI^ JKH];'
'[ZBC^ YEF];[XHI^ UKH];'
or perhaps:
>> B = regexprep(A,'(?<!\]);(?!\[)','^')
B =
'[ABC^ DEF];[GHI^ JKH];'
'[ZBC^ YEF];[XHI^ UKH];'

6 comentarios

Thanks Stephen
What if we have more than one ";" in a cell
e.g
>> A = {'[ABC; DEF; LMN];[GHI; JKH; OPQ; RST];'; '[ZBC; YEF; UVW; XYY; DFF; TRR];[XHI; UKH];'}
Stephen23
Stephen23 el 2 de Mzo. de 2020
"What if we have more than one ";" in a cell"
Then you need to specify the expected output. I cannot guess what you want.
Muhammad Rahil Rafiq
Muhammad Rahil Rafiq el 2 de Mzo. de 2020
Editada: Muhammad Rahil Rafiq el 2 de Mzo. de 2020
My apologies.
Your earlier command is replacing only one last char ";".
I need to replace all ";" within square brackets
>> A = {'[ABC; DEF; LMN];[GHI; JKH; OPQ; RST];'; '[ZBC; YEF; UVW; XYY; DFF; TRR];[XHI; UKH];'}
A =
'[ABC; DEF; LMN];[GHI; JKH; OPQ; RST];'
'[ZBC; YEF; UVW; XYY; DFF; TRR];[XHI; UKH];'
>> B = regexprep(A,'(\[[^\]]+\])','${strrep($1,'';'',''^'')}')
B =
'[ABC^ DEF^ LMN];[GHI^ JKH^ OPQ^ RST];'
'[ZBC^ YEF^ UVW^ XYY^ DFF^ TRR];[XHI^ UKH];'
Thanks again!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Centro de ayuda y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by