0

I'm trying to cut some strings which contains the symbol '_' using STRMATCH and STRSPLIT, in order to modify them, in this way:

mystring=['aaa_111','bbb_222','ccc','ddd']
nmax=N_ELEMENTS(mystring)
cut_mystring=STRARR(2,nmax)

FOR i=0, nmax-1 DO BEGIN
  IF (STRMATCH(mystring[i], '*_*') eq 1) THEN BEGIN
    cut_mystring[i]=STRSPLIT(mystring[i], '_', /EXTRACT)
    mystring_new[i]= cut_mystring[0,i]+'_MYCOMMENT_'+cut_mystring[1,i]
  ENDIF
ENDFOR
print, mystring_new[i]

The result of print, mystring_new[i] is:

aaa_111
222_MYCOMMENT_
ccc
ddd

So, it seems to work for the first element (and of course for the last two, too), but not for the second.

What am I doing wrong here? Thanks!

pdw
  • 8,359
  • 2
  • 29
  • 41
Alberto
  • 341
  • 1
  • 3
  • 13
  • [SOLVED]Solution: cut_mystring=STRSPLIT(mystring[i], '_', /EXTRACT) mystring_new[i]=cut_mystring[0]+'_MYCOMMENT_'+cut_mystring[1] – Alberto Jul 15 '14 at 10:10

1 Answers1

1

Perhaps this would be easier using a regex?

mystring = ['aaa_111','bbb_222','ccc','ddd']
r = stregex(mystring, '([^_]*)(.*)?', /extract, /subexpr)
mystring_new = reform(r[1, *] + '_MYCOMMENT' + r[2, *])

Which outputs:

IDL> for i = 0, 3 do print, mystring_new[i]
aaa_MYCOMMENT_111
bbb_MYCOMMENT_222
ccc_MYCOMMENT
ddd_MYCOMMENT

The regex is ([^_]*)(.*). ([^_]*) matches a span of characters except underscore into one group. (.*) matches everything else left in the string, including any underscores, into the second group.

Pi Marillion
  • 4,465
  • 1
  • 19
  • 20