匹配正则表达式并反转目标字符串中的匹配项

匹配正则表达式并反转目标字符串中的匹配项

问题描述:

基于这个问题 正则表达式 \d+(?:-\d+)+ 将匹配这个 10-3-15-0.

Based on this question Regex \d+(?:-\d+)+ will match this 10-3-1 and 5-0.

示例:

This is 10-3-1 my string

执行匹配和反转后,我希望它是这样的:

After performing the matching and reversing, I want it to be like this:

This is 1-3-10 my string

请注意,10-3-1 应该变成 1-3-10,而不是正常的字符串反转,这会导致 1-3-01.

Notice that 10-3-1 should become 1-3-10 and not normal string reverse which would result in 1-3-01.

一个基本的算法是:

  1. 从字符串中提取匹配项.10-3-1"
  2. 用-"字符将匹配分割成一段.
  3. 您现在有一个元素列表.["10","3","1"]
  4. 反转列表.["1","3","10"]
  5. 使用-"字符连接数组元素.1-3-10"
  6. 用新加入的字符串替换匹配项.