Grab part of the text that is between tags of a string

Asked

Viewed 2,375 times

0

I have the following string:

Meu nome é <nome> Nickolas Carlos<nome>

I wanted to know how I can do in VB.NET to get only what is between the tags <nome> which in this case would be: Nickolas Carlos

It is possible to do this using only VB.NET?

  • Would not be <nome> and </nome>?

  • Yes, it might be too!

3 answers

1

A possibility would be:

Sub Main()
    Dim minhaString = "Meu nome é <nome>Nicolas Carlos da Silva<nome>"
    Dim nome = minhaString.Substring(minhaString.IndexOf(">") + 1, minhaString.LastIndexOf("<") - minhaString.IndexOf(">") - 1)
    Debug.Print(nome)
End Sub

0


An option using regex:

Imports System.Text.RegularExpressions
Module VBModule
    Sub Main()
        Dim str As String = "Meu nome é <nome> Nickolas Carlos<nome>"
        Dim pad As New Regex("(?<=<nome> ).+(?=<nome>)")
        Dim nome As String = pad.Match(str).value
        Console.WriteLine(nome)
    End Sub
End Module

Just be careful with the spaces. In this case, it is considering a space after <nome> and none after the name.

0

I know how to do this in C#... but I think you will not have problems in converting to VB.Net:

string texto = "xpto <nome> abc </nome>";
var match = Regex.Match(texto, @"\<nome\>\s*(.+?)\s*?\<\/nome\>");
var nome = match.Success ? match.Groups[1].Value : null;

The return will be abc in the above example.

regex is efficient because I use operators *? and +? who try to match the smaller alternatives first instead of the larger ones first (which would be the case for operators * and +)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.