replacing gramatical characters

Smee

Well-Known Member
Licensed User
Longtime User
i need to test some strings for the occurrence of commas ful stops and even erroneous double spaces.

I am using this code

B4X:
st=edtName.Text

If st.Contains(",")=True Then
   st=st.Replace(","," ")
End If
If st.Contains("  ")=True Then
   st=st.Replace("  "," ")
End If

Which is very inelegant and will be cumbersome to say the least. Is there a better way to search for a sting of 'bad' charcters or ascii codes and replace them initially with a space and then do a check for replacing double/triple spaces with a single space?

Thanks
 

NJDude

Expert
Licensed User
Longtime User
You will need to use Regular Expressions:
B4X:
Dim BadChars As String
Dim Text As String
Dim Matcher1 As Matcher

BadChars = "[.,+*;]" 'Add the unwanted characters here between the square brackets
            
Text = "Some, list + of words; some not wanted like * for example."
            
Matcher1 = Regex.Matcher(BadChars, Text)
            
Do While Matcher1.Find
         
   buffer = Matcher1.Match
   Text = Text.Replace(buffer, "")

Loop
            
Msgbox("Done: " & Text, "")
 
Upvote 0

Smee

Well-Known Member
Licensed User
Longtime User
BRILLIANT!!!

Exactly what i needed. Thanks v much for that NJDude.

:sign0060:
 
Upvote 0

pozzari

New Member
Licensed User
Longtime User
good chars

Is there a way to replace Badchars to Goodchars? Because i want chars from A to Z, a to z and 0 to 9.
Thanks a lot
 
Upvote 0

Mahares

Expert
Licensed User
Longtime User
If you want to keep only upper and lower case characters and numbers, eliminating everything else, here is the code.

B4X:
   Dim GoodChars As String
   Dim Text,Buffer, TextClean As String
   Dim Matcher1 As Matcher
   GoodChars = "[a-zA-Z0-9]" 'wanted characters only between square brackets
   Text = "Some, list + of 43 words; some & ! not wanted . like * for ~ example."
   Matcher1 = Regex.Matcher(GoodChars, Text)                
   Do While Matcher1.Find
      Buffer = Matcher1.Match
      TextClean = TextClean & Buffer
   Loop
   Msgbox("Clean Text: " & TextClean & CRLF & "Original Text: " & Text , "")
I hope I understood your question. Hopefully, we get NJDude's blessings.
 
Upvote 0
Top