我有以下字符串:
[bla.FormatException, 96][bla, 22][ResourceNotFoundException, 48]
我需要把它做成这样:
['bla.FormatException', 96],
['bla', 22],
['ResourceNotFoundException', 48]
现在我在做这个:
textToAdd.replace("][","],n[").replace("[","['").replace(", ","', ")
它有效,但看起来很漂亮,如果有一个小的变化,甚至额外的空间,它可能会坏掉。。我可以使用regex进行操作以使其更清楚吗?
Regex和多重赋值在这里提供帮助:
String text = '[bla.FormatException, 96][bla, 22][ResourceNotFoundException, 48]'
String result = ( text =~ /([([^,[]]+), (d+)])/ ).findAll().collect{ _, __, name, number -> "['$name', $number]" }.join( ',n' )
assert result == '''
['bla.FormatException', 96],
['bla', 22],
['ResourceNotFoundException', 48]'''