locked
how can i extract only letters from text? RRS feed

  • Question

  •       Dim value = "only42letter"

            Dim m As Match = Regex.Match(value, _
                    "([A-Za-z]+)", _
                   RegexOptions.IgnoreCase)
            If (m.Success) Then
            Dim key As String = m.Groups(1).Value
            MsgBox(key)
            End If

    i need to make value "onlyletter" by excluding "42". but key returning "only" or "letter". how can i get whole letters but numbers?

    Thursday, December 13, 2012 3:05 PM

Answers

  • Hi, you can use Regex.Replace to get the string without numbers:
    Dim input As String = "only42string"
    
    Dim output As String = Regex.Replace(input, "[\d]", String.Empty)


    Koopakiller [kuːpakɪllɐ] http://koopakiller.ko.ohost.de/

    • Proposed as answer by Blackwood Thursday, December 13, 2012 3:46 PM
    • Marked as answer by ulasank Saturday, December 15, 2012 2:20 PM
    Thursday, December 13, 2012 3:14 PM
  • this String.Join certainly works with Option Strict On, but I could have used this String.Concat and drop the call at ToArray in your code ;)


    that only works with 4+ framework. i tested it in vb2008

    thanks for any help

    • Marked as answer by ulasank Saturday, December 15, 2012 2:19 PM
    Friday, December 14, 2012 9:03 AM

All replies

  • Hi, you can use Regex.Replace to get the string without numbers:
    Dim input As String = "only42string"
    
    Dim output As String = Regex.Replace(input, "[\d]", String.Empty)


    Koopakiller [kuːpakɪllɐ] http://koopakiller.ko.ohost.de/

    • Proposed as answer by Blackwood Thursday, December 13, 2012 3:46 PM
    • Marked as answer by ulasank Saturday, December 15, 2012 2:20 PM
    Thursday, December 13, 2012 3:14 PM
  • Alternative without regex:

    Dim input = "only42letters"
    
    Dim output = String.Join(String.Empty, input.Where(AddressOf Char.IsLetter))

    Thursday, December 13, 2012 5:35 PM
  • Alternative without regex:

    Dim input = "only42letters"
    
    Dim output = String.Join(String.Empty, input.Where(AddressOf Char.IsLetter))

    good idea but your code won't run with Option Strict on.

    String.Join joins a string array + you're passing it an IEnumerable(Of Char).

    try this:

    Dim input = "only42letters"
    Dim output = String.Concat(input.Where(AddressOf Char.IsLetter).ToArray)


    thanks for any help

    Friday, December 14, 2012 6:42 AM
  • this String.Join certainly works with Option Strict On, but I could have used this String.Concat and drop the call at ToArray in your code ;)

    Friday, December 14, 2012 8:51 AM
  • this String.Join certainly works with Option Strict On, but I could have used this String.Concat and drop the call at ToArray in your code ;)


    that only works with 4+ framework. i tested it in vb2008

    thanks for any help

    • Marked as answer by ulasank Saturday, December 15, 2012 2:19 PM
    Friday, December 14, 2012 9:03 AM