使用XE货币的正则表达式

时间:2016-03-28 17:15:36

标签: regex vb.net

伙计们我正在尝试使用VB.Net创建我的个人应用程序

我的所有代码都工作正常,除了一件事,即正则表达式

我想得到这个值

The Highlighted Value that I need

从此URL

我试过这个正则表达式:

("([0-9]+.+[1-9]+ (SAR)+)")

并且效果不佳(仅适用于部分货币但不适用于所有货币)。

所以你们可以帮助完美的正则表达式吗?

***更新: 这是整个功能代码:

Private Sub doCalculate()
    ' Need the scraping
    Dim Str As System.IO.Stream
    Dim srRead As System.IO.StreamReader
    Dim strAmount As String
    strAmount = currencyAmount.Text

    ' Get values from the textboxes
    Dim strFrom() As String = Split(currecnyFrom.Text, " - ")
    Dim strTo() As String = Split(currecnyTo.Text, " - ")

    ' Web fetching variables
    Dim req As System.Net.WebRequest = System.Net.WebRequest.Create("https://www.xe.com/currencyconverter/convert.cgi?template=pca-new&Amount=" + strAmount + "&From=" + strFrom(1) + "&To=" + strTo(1) + "&image.x=39&image.y=9")
    Dim resp As System.Net.WebResponse = req.GetResponse

    Str = resp.GetResponseStream
    srRead = New System.IO.StreamReader(Str)


    ' Match the response
    Try
        Dim myMatches As MatchCollection
        Dim myRegExp As New Regex("(\d+\.\d+ SAR)")

        myMatches = myRegExp.Matches(srRead.ReadToEnd)

        ' Search for all the words in the string
        Dim sucessfulMatch As Match
        For Each sucessfulMatch In myMatches
            mainText.Text = sucessfulMatch.Value
        Next
    Catch ex As Exception
        mainText.Text = "Unable to connect to XE"
    Finally
        ' Close the streams
        srRead.close()
        Str.Close()
    End Try
    convertToLabel.Text = strAmount + " " + strFrom(0) + " Converts To: "
End Sub

感谢。

2 个答案:

答案 0 :(得分:1)

你应该使用这个正则表达式。

正则表达式: (\d+\.\d+ SAR)

<强>解释

  • \d+查找多个数字。

  • \.\d+查找十进制数字。

  • SAR匹配文字字符串SAR,这是您的货币单位。

<强> Regex101 Demo

  

我试过这个正则表达式:

     

(&#34;([0-9] +。+ [1-9] +(SAR)+)&#34;)并且效果不佳(仅适用)   用一些货币但不是全部货币。)

您在这里做的是匹配multiple digits anything multiple digits SAR multiple times.

答案 1 :(得分:0)

您需要获取首先出现的货币值。因此,您需要替换

myMatches = myRegExp.Matches(srRead.ReadToEnd)
' Search for all the words in the string
Dim sucessfulMatch As Match
For Each sucessfulMatch In myMatches
    mainText.Text = sucessfulMatch.Value
Next

使用以下行:

Dim myMatch As Match = myRegExp.Match(srRead.ReadToEnd)
mainText.Text = myMatch.Value

我还建议使用following regex

\b\d+\.\d+\p{Zs}+SAR\b

说明:

  • \b - 字边界
  • \d+ - 1+位数
  • \. - 一个文字点
  • \d+ - 1+位数
  • \p{Zs}+ - 一个或多个水平空格
  • SAR\b - 整个字SAR