Results 1 to 12 of 12

Thread: [RESOLVED] how can i check in a sentence a specific word to see if exists

  1. #1

    Thread Starter
    Enjoy the moment
    Join Date
    Feb 2011
    Location
    Barrio Del pilar madrid spain
    Posts
    5,204

    Resolved [RESOLVED] how can i check in a sentence a specific word to see if exists

    hey,
    E.X
    Code:
    salsa is going to shop
    i need to find if going exists in the sentence .
    how do i do that?
    thanks for any help
    salsa
    Last edited by salsa31; Dec 13th, 2017 at 01:05 AM.

  2. #2
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,855

    Re: how can i check in a sentence a specific word to see if exists

    Hi Salsa,

    To my eyes, this is sort of the classic use of Instr(). However, there are a few things to consider, depending on exactly what you're wanting. For instance, the case (upper or lower), as well as whether the word being a part of a larger word is acceptable.

    The case issue is easily solved with LCase$() or UCase$(). But the "within larger word" issue is a bit trickier. If it were me, I'd possibly add a space to the beginning and ending of the sentence, and then search for " going " (notice prefix and suffix spaces). Adding the spaces to the sentence allows you to find your " going " string even if it's at the start or end of the sentence.

    Good Luck,
    Elroy

    EDIT1: Also, if there are embedded vbTab or vbCrLf type characters in your sentence, that's another problem. You could use Replace$() to replace all of that kind of stuff you think you'll run across. Punctuation (period, comma, semi-colon) are other possible problems.
    Last edited by Elroy; Dec 12th, 2017 at 09:41 AM.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  3. #3
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    14,205

    Re: how can i check in a sentence a specific word to see if exists

    You can get by without using LCase$() or UCase$() by adding the optional parameters to INSTR()

    You can also get around the whole word by doing two checks one with a leading space and one with a trailing space to cover instances where the word would be the first or last word in the sentence though that would fail if it is the only word in the sentence.
    Code:
    Dim searchin As String
    searchin = "i need to find if going exists in the sentence ."
    If InStr(1, searchin, " going", vbTextCompare) Or InStr(1, searchin, "going ", vbTextCompare) Then
        MsgBox "is there"
    Else
        MsgBox "not there"
    End If

  4. #4
    PowerPoster SamOscarBrown's Avatar
    Join Date
    Aug 2012
    Location
    NC, USA
    Posts
    9,145

    Re: how can i check in a sentence a specific word to see if exists

    salsa

    yes, easy stuff (basically)
    Put a RichTextBox on a new form, name it rtb1. Put a text box on the form and set its text value to 'aid'
    add a command button

    put this code in the form, and then run it and click the command button

    Code:
    Option Explicit
    
    Private Sub Command1_Click()
        Dim mWord As String
        Dim mSentence As String
        mWord = " " & UCase(Text1.Text) & " "
        mSentence = " " & UCase(rtb1.Text) & " "
        Dim i As Integer
        i = InStr(1, mSentence, mWord)
        If i > 0 Then
            MsgBox "Your search for '" & Text1.Text & "' in '" & rtb1.Text & "' was successful!"
        Else
            MsgBox "Sorry...no matches."
        End If
    End Sub
    
    
    Private Sub Form_Load()
        rtb1.Text = "Now is the time for all good men to come to the aid of their party."
    End Sub
    Now, why I used a richtextbox is because if you want to SEE that word found, say, in RED, the RTB is a great component to use for doing that. I did NOT write that code, but it is easy to do...if you want to do it, look up the RTB .textrtf and how to display some of it in colors

  5. #5
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: how can i check in a sentence a specific word to see if exists

    TOM is helpful for this.

    Code:
    Option Explicit
    
    Private Const WM_USER As Long = &H400&
    Private Const EM_GETOLEINTERFACE As Long = WM_USER + 60
    
    Private Declare Function SendMessage Lib "user32" Alias "SendMessageW" ( _
        ByVal hWnd As Long, _
        ByVal wMsg As Long, _
        ByVal wParam As Long, _
        ByVal lParam As Long) As Long
    
    Private tdRTB As tom.ITextDocument
    
    Private Sub Command_Click()
        Dim Found As Boolean
    
        With tdRTB.Range(0, -1)
            Do While .FindText(Text.Text, tomForward, tomMatchWord)
                Found = True
                .Font.BackColor = vbYellow
                .MoveStart 1, tomWord
            Loop
        End With
        Label.Caption = CStr(Found)
    End Sub
    
    Private Sub Form_Load()
        Dim IUnknown As stdole.IUnknown
    
        SendMessage RTB.hWnd, EM_GETOLEINTERFACE, 0, VarPtr(IUnknown)
        Set tdRTB = IUnknown
    End Sub
    
    Private Sub Form_Resize()
        If WindowState <> vbMinimized Then
            With Frame
                .Move 0, ScaleHeight - .Height, ScaleWidth
                RTB.Move 0, 0, ScaleWidth, .Top
            End With
        End If
    End Sub

    Name:  sshot.png
Views: 158
Size:  2.2 KB
    Attached Files Attached Files

  6. #6

    Thread Starter
    Enjoy the moment
    Join Date
    Feb 2011
    Location
    Barrio Del pilar madrid spain
    Posts
    5,204

    Re: how can i check in a sentence a specific word to see if exists

    thats Great!!
    thank you guys

  7. #7
    PowerPoster SamOscarBrown's Avatar
    Join Date
    Aug 2012
    Location
    NC, USA
    Posts
    9,145

    Re: [RESOLVED] how can i check in a sentence a specific word to see if exists

    That is simply amazing, dile...think salsa can grasp?

  8. #8
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,046

    Re: how can i check in a sentence a specific word to see if exists

    Quote Originally Posted by dilettante View Post
    TOM is helpful for this.

    Code:
    Option Explicit
    
    Private Const WM_USER As Long = &H400&
    Private Const EM_GETOLEINTERFACE As Long = WM_USER + 60
    
    Private Declare Function SendMessage Lib "user32" Alias "SendMessageW" ( _
        ByVal hWnd As Long, _
        ByVal wMsg As Long, _
        ByVal wParam As Long, _
        ByVal lParam As Long) As Long
    
    Private tdRTB As tom.ITextDocument
    
    Private Sub Command_Click()
        Dim Found As Boolean
    
        With tdRTB.Range(0, -1)
            Do While .FindText(Text.Text, tomForward, tomMatchWord)
                Found = True
                .Font.BackColor = vbYellow
                .MoveStart 1, tomWord
            Loop
        End With
        Label.Caption = CStr(Found)
    End Sub
    
    Private Sub Form_Load()
        Dim IUnknown As stdole.IUnknown
    
        SendMessage RTB.hWnd, EM_GETOLEINTERFACE, 0, VarPtr(IUnknown)
        Set tdRTB = IUnknown
    End Sub
    
    Private Sub Form_Resize()
        If WindowState <> vbMinimized Then
            With Frame
                .Move 0, ScaleHeight - .Height, ScaleWidth
                RTB.Move 0, 0, ScaleWidth, .Top
            End With
        End If
    End Sub

    Name:  sshot.png
Views: 158
Size:  2.2 KB
    great !!

    regards
    Chris
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  9. #9
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: [RESOLVED] how can i check in a sentence a specific word to see if exists

    Look up ITextDocument in your MSDN Library CD online docs. If you have the October 2001 version installed (and maybe some earlier ones) the TOM documentation is there.

    A little incomplete, and slightly wrong in a few places (some TOM methods used to have optional parameters but haven't in a very long time). More current info can be found at the MSDN web site but most of the VB6 examples have been removed.

    RichEdit controls and Word both implement TOM as an object model, though some things only work in Word.

  10. #10
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,046

    Re: [RESOLVED] how can i check in a sentence a specific word to see if exists

    Hi dilettante,

    I really don't know why I missed ITextDocument all these years, just shows you
    that you can still learn something , evan a old Horse like me.

    regards
    Chris
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  11. #11
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    5,121

    Re: [RESOLVED] how can i check in a sentence a specific word to see if exists

    I would probably use regular expression's word boundary metacharacter \b for checking word existence in a string.

    Here is a simple regexp "library" designed to emulate PHP's preg functions sort of, with a sample usage and a somewhat complicated test-case (punctuation as first boundary, end-of-string as second)
    vb Code:
    1. Option Explicit
    2.  
    3. Private Sub Form_Load()
    4.     Dim sText           As String
    5.     Dim sWord           As String
    6.     Dim vIndexes        As Variant
    7.    
    8.     sText = "salsa is going to shop.going"
    9.     sWord = "going"
    10.     If preg_match("\b" & preg_escape(sWord) & "\b", sText, Indexes:=vIndexes) > 0 Then
    11.         Debug.Print "Found at positions: " & Join(vIndexes, ", ")
    12.         Debug.Print "First occurrence: " & Mid$(sText, vIndexes(0))
    13.     End If
    14. End Sub
    15.  
    16. Public Function InitRegExp(sPattern As String) As Object
    17.     Dim lPos            As Long
    18.    
    19.     Set InitRegExp = CreateObject("VBScript.RegExp")
    20.     With InitRegExp
    21.         lPos = InStrRev(sPattern, "/")
    22.         If Left$(sPattern, 1) = "/" And lPos > 1 Then
    23.             .Pattern = Mid$(sPattern, 2, lPos - 2)
    24.             .IgnoreCase = (InStr(lPos, sPattern, "i") > 0)
    25.             .MultiLine = (InStr(lPos, sPattern, "m") > 0)
    26.             .Global = (InStr(lPos, sPattern, "l") = 0)
    27.         Else
    28.             .Global = True
    29.             .Pattern = sPattern
    30.         End If
    31.     End With
    32. End Function
    33.  
    34. Public Function preg_match(find_re As String, sText As String, Optional Matches As Variant, Optional Indexes As Variant) As Long
    35.     Dim lIdx            As Long
    36.    
    37.     With InitRegExp(find_re).Execute(sText)
    38.         preg_match = .Count
    39.         If Not IsMissing(Matches) Then
    40.             If .Count = 0 Then
    41.                 Matches = Split(vbNullString)
    42.             ElseIf .Count = 1 Then
    43.                 ReDim Matches(0 To 0) As String
    44.                 Matches(0) = .Item(0).Value
    45.             Else
    46.                 ReDim Matches(0 To .Count - 1) As String
    47.                 For lIdx = 0 To .Count - 1
    48.                     Matches(lIdx) = .Item(lIdx).Value
    49.                 Next
    50.             End If
    51.         End If
    52.         If Not IsMissing(Indexes) Then
    53.             If .Count = 0 Then
    54.                 Indexes = Array()
    55.             ElseIf .Count = 1 Then
    56.                 Indexes = Array(.Item(0).FirstIndex + 1)
    57.             Else
    58.                 ReDim Indexes(0 To .Count - 1) As Variant
    59.                 For lIdx = 0 To .Count - 1
    60.                     Indexes(lIdx) = .Item(lIdx).FirstIndex + 1
    61.                 Next
    62.             End If
    63.         End If
    64.     End With
    65. End Function
    66.  
    67. Public Function preg_replace(find_re As String, sText As String, Optional sReplace As String) As String
    68.     preg_replace = InitRegExp(find_re).Replace(sText, sReplace)
    69. End Function
    70.  
    71. Public Function preg_split(find_re As String, sText As String) As Variant
    72.     Dim esc             As String
    73.    
    74.     esc = ChrW$(&HE1B6) '-- U+E000 to U+F8FF - Private Use Area (PUA)
    75.     preg_split = Split(InitRegExp(find_re).Replace(sText, esc), esc)
    76. End Function
    77.  
    78. Public Function preg_escape(find_re As String) As String
    79.     preg_escape = InitRegExp("[.*+?^${}()/|[\]\\]").Replace(find_re, "\$&")
    80. End Function
    cheers,
    </wqw>
    Last edited by wqweto; Dec 14th, 2017 at 02:46 AM.

  12. #12
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,046

    Re: [RESOLVED] how can i check in a sentence a specific word to see if exists

    Hi,

    might as well put my simple way in here...

    Code:
    Private Sub Command1_Click()
    
       Dim SearchMethod As Boolean
       Dim i As Long
       
          SearchMethod = CBool(Check1.Value * -1)
          i = FindString(RichTextBox1, Text1.Text, , SearchMethod)
          Print i
          
          RichTextBox1.SetFocus
    End Sub
    
    Private Sub Form_Load()
    
          Check1.Caption = "SearchForward"
          Check1.Value = 1
          
          RichTextBox1.Text = "salsa is going to shop,salsa is Going to shop"
          RichTextBox1.HideSelection = False
          Text1.Text = "going"
    End Sub
    
    '-----------------------------------------------
    'suchen in einer RTF-Box, optional mit Markieren
    '-----------------------------------------------
    Public Function FindString(RTF As RichTextBox, _
                               sString As String, _
                               Optional CompareAs As VbCompareMethod = _
                               vbTextCompare, _
                               Optional SearchForward _
                               As Boolean = True, _
                               Optional SelText As _
                               Boolean = True) As Long
    
       Dim i As Long
       
          'suchen vorwärts
          If SearchForward Then
             i = RTF.SelStart + RTF.SelLength + 1
             i = InStr(i, RTF.Text, sString, CompareAs)
          'suchen rückwärts
          Else
             i = RTF.SelStart - RTF.SelLength
             i = InStrRev(RTF.Text, sString, i, CompareAs)
          End If
          'gefunden an Position (0=nicht gefunden)
          FindString = i
          
          'markieren gefundenen Text
          If SelText Then
             With RTF
                'wenn gefunden
                If i > 0 Then
                   .SelStart = i - 1
                   .SelLength = Len(Text1.Text)
                'wenn nicht gefunden
                Else
                   'Cursor an Textende
                   If SearchForward Then
                      .SelStart = Len(.Text)
                      .SelLength = 0
                   'Cursor an Textanfang
                   Else
                      .SelStart = 0
                      .SelLength = 0
                   End If
                End If
             End With
          End If
    End Function
    regards
    Chris
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width