仅将混合字符串中的数字相乘[VB.Net]

时间:2016-01-25 01:14:29

标签: regex vb.net

我们说我有一个字符串" N4NSD3MKF34MKMKFM53"我想将字符串* 2乘以得到

N8NSD6MKF68MKMKFM106我该怎么做呢?

2 个答案:

答案 0 :(得分:3)

好的,只要我在这里,我不妨给你正则表达式解决方案。但我提醒你不要使用它,除非你明白它在做什么。复制和粘贴您不完全理解的代码绝不是一个好主意。

Dim input As String = "N4NSD3MKF34MKMKFM53"
Dim output As String = Regex.Replace(
                                 input, 
                                 "\d+", 
                                 Function(x) (Integer.Parse(x.Value) * 2).ToString())

答案 1 :(得分:0)

您可以尝试以下代码:

Public Class Program
Public Shared Sub Main(args As String())

        Const  expression As String = "N4NSD3MKF34MKMKFM53"

        Dim  result = MultiplyExpression.Calculate(expression)
        Console.WriteLine(result)
    End Sub
End Class

Class MultiplyExpression
    Public Shared Function Calculate(expression As String) As String
        Dim result = String.Empty
        For  Each c In expression
            Dim num As Integer
            If Int32.TryParse(c.ToString(), num) Then
                result += (num * 2).ToString()
            Else
                result += c
            End If
        Next

        Return result
    End Function
End Class

输出:N8NSD6MKF68MKMKFM106