How do check that a string only consists of letters?########################################################################################################################################################################################################################################################
Here's a way to check if a string contains only letters:
Dim text As String = "abcd"
Dim flag As Boolean = text.AsEnumerable().All(Function(c As Char) Char.IsLetter(c))
You would use String.Contains() This exsplains how to use it, http://vb.net-informations.com/string/vb.net_String_Contains.htm
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
str = "VB.NET TOP 10 BOOKS"
If str.Contains("TOP") = True Then
MsgBox("The string Contains() 'TOP' ")
Else
MsgBox("The String does not Contains() 'TOP'")
End If
End Sub
End Class
Edit: I'm not sure why your post includes a lot of #'s, is it an example of the text your looking to check over? :3
Public Function isValid(ByVal str As String) As Boolean
Dim pattern As String = "^[a-zA-Z\s]+$"
Dim reg As New Regex(pattern)
Return reg.IsMatch(str)
End Function
This could possibly be the solution your after.
You want to use a regular expression like in this question:
C# Regex: Checking for "a-z" and "A-Z"
The vb should be very similar:
private function isValid(byval str as String) as Boolean
return Regex.IsMatch(str, #"^[a-zA-Z]+$")
End Function
Related
I keep getting this error, I tried all I could but it still says "Value type of String() cannot be converted to string."
Here is the code:
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
Sub New()
InitializeComponent()
RAN = New Random
WB = New WebClient
End Sub
Private Const IDNum As String = "https://example.com/Data.php"
Private WB As WebClient
Private RAN As Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Account As String() = WB.DownloadString(IDNum).Split(Environment.NewLine)
AccSplit(Account(RAN.Next(1, Account.Length)))
End Sub
Private Sub AccSplit(ByVal Account As String)
TextBox2.Text = Account.Split()
End Sub
When you call Split here:
TextBox2.Text = Account.Split()
You are getting a String array back. Calling Split with no arguments will split the String on whitespace characters. For instance, this:
Dim arr = "Hello World".Split()
is equivalent to this:
Dim arr = {"Hello", "World"}
The Text property of a TextBox is type String, so you can't assign a String array to it. That doesn't make sense. If you want to fry an egg, do you put am egg carton in the pan? The correct course of action depends on what you're actually trying to achieve. If you just want that String displayed in the TextBox then do this:
TextBox2.Text = Account
You could also do this:
TextBox2.Lines = Account.Split()
to display the array with the elements on separate lines in the TexTbox, which assumes that you have set its Multiline property to True.
TextBox2.Text is a string. The string.Split() function returns an array of strings (shown by Visual Studio as a string()). Those types don't match up. You can't just assign an array to a string. I might ask if you wanted this:
TextBox2.Text = String.Join(",", Account.Split())
That will at least compile. But it makes no sense... why split a string, just to join it back again?
i have a program that replace ing in some string and its return original verb in that srting like he was playing out door will be he was play out door ...etc
i just want the play without whole string
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myInput As String = TextBox1.Text
Dim myOutput As String = Replace(myInput, "ing", "")
Label1.Text = myOutput
End Sub
Private Function getVerbOfSetence(ByVal str As String) As String
Dim strSpl() As String = str.Split(" ")
For i = 0 To strSpl.Length - 1
If strSpl(i).ToLower.EndsWith("ing") Then
Return strSpl(i).ToLower.Replace("ing", "")
End If
Next
Return "noVerb"
End Function
The fastest way is to use a one-line Regex.
Dim Output As String = Regex.Match(myInput, "\p{L}+(?=ing[^\p{L}])", RegexOptions.IgnoreCase).Value
A Regex is a class capable of matching strings based on patterns. It's great to use and usually very fast. The pattern is the second string which I've passed to the Match() method. My pattern works like this:
The \p{L}+ part means that it should match every character that is a unicode letter. + means that it should match one or more letters.
The (?=ing[^\p{L}]) part means that the match must end with "ing", and that it's not followed by any unicode letters.
To match multiple verbs we'd have to expand this a bit. Putting it into a function. The function will find all substrings that match the specified pattern, and then put them in a string array and return it to you.
Public Function FindVerbs(ByVal Input As String) As String()
Dim Matches As MatchCollection = Regex.Matches(Input, "\p{L}+(?=ing[^\p{L}])", RegexOptions.IgnoreCase)
Dim ReturnArray(Matches.Count - 1) As String
For x = 0 To Matches.Count - 1
ReturnArray(x) = Matches(x).Value
Next
Return ReturnArray
End Function
Function example usage:
Dim Verbs() As String = FindVerbs("I am playing with my helicopter. It's flying very fast.")
Console.WriteLine(Verbs(0)) 'Prints "play"
Console.WriteLine(Verbs(1)) 'Prints "fly"
Example: http://ideone.com/6TeAmz
Best way is to replace whole word. You put in word in textbox that you want to add ing to it
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myInput As String = TextBox1.Text
Dim myOutput As String = StringToReplacePart.Replace(myInput, String.Format("{0}ing", myInput)
Label1.Text = myOutput
End Sub
So my problem is:
I have a List of a custom Type {Id as Integer, Tag() as String},
and i want to perform a multiple-criteria search on it; eg:
SearchTags={"Document","HelloWorld"}
Results of the Search will be placed a ListBox (ListBox1) in this format:
resultItem.id & " - " & resultItem.tags
I already tried everything i could find on forums, but it didn't work for me (It was for db's or for string datatypes)
Now, i really need your help. Thanks in advance.
For Each MEntry As EntryType In MainList
For Each Entry In MEntry.getTags
For Each item As String In Split(TextBox1.Text, " ")
If Entry.Contains(item) Then
If TestIfItemExistsInListBox2(item) = False Then
ListBox1.Items.Add(item & " - " & Entry.getId)
End If
End If
Next
Next
Next
Example Custom Array:
(24,{"snippet","vb"})
(32,{"console","cpp","helloworld"})
and so on...
I searched for ("Snippet vb test"):
snippet vb helloWorld - 2
snippet vb tcpchatEx - 16
cs something
test
So, i'll get everything that contains one of my search phrases.
I expected following:
snippet vb tcp test
snippet vb dll test
snippet vb test metroui
So, i want to get everything that contains all my search phrases.
My entire, code-likely class
Imports Newtonsoft.Json
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Dim MainList As New List(Of EntryType)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MainList.Clear()
Dim thr As New Threading.Thread(AddressOf thr1)
thr.SetApartmentState(Threading.ApartmentState.MTA)
thr.Start()
End Sub
Delegate Sub SetTextCallback([text] As String)
Private Sub SetTitle(ByVal [text] As String) ' source <> mine
If Me.TextBox1.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetTitle)
Me.Invoke(d, New Object() {[text]})
Else
Me.Text = [text]
End If
End Sub
Sub thr1()
Dim linez As Integer = 1
Dim linex As Integer = 1
For Each line As String In System.IO.File.ReadAllLines("index.db")
linez += 1
Next
For Each line As String In System.IO.File.ReadAllLines("index.db")
Try
Application.DoEvents()
Dim a As saLoginResponse = JsonConvert.DeserializeObject(Of saLoginResponse)(line) ' source <> mine
Application.DoEvents()
MainList.Add(New EntryType(a.id, Split(a.tags, " ")))
linex += 1
SetTitle("Search (loading, " & linex & " of " & linez & ")")
Catch ex As Exception
End Try
Next
SetTitle("Search")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim searchTags() As String = TextBox1.Text.Split(" ")
Dim query = MainList.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
ListBox1.Items.Add(et.Id)
Next
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) ' test
MsgBox(Mid(ListBox1.SelectedItem.ToString, 1, 6)) ' test
End Sub 'test, removeonrelease
End Class
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As String
Public Sub New(ByVal _id As Integer, ByVal _tags() As String)
Me.Id = Id
Me.Tags = Tags
End Sub
Public Function GetTags() As String
'to tell the Listbox what to display
Return Tags
End Function
Public Function GetId() As Integer
'to tell the Listbox what to display
Return Id
End Function
End Class
I also edited your EntryType class; I added a constructor, removed toString and added GetTags and GetID.
Example "DB" im working with ("db" as "index.db" in exec dir):
{"tags":"vb.net lol test qwikscopeZ","id":123456}
{"tags":"vb.net lol test","id":12345}
{"tags":"vb.net lol","id":1234}
{"tags":"vb.net","id":123}
{"tags":"cpp","id":1}
{"tags":"cpp graphical","id":2}
{"tags":"cpp graphical fractals","id":3}
{"tags":"cpp graphical fractals m4th","id":500123}
Error:
Debugger:Exception Intercepted: _Lambda$__1, Form2.vb line 44
An exception was intercepted and the call stack unwound to the point before the call from user code where the exception occurred. "Unwind the call stack on unhandled exceptions" is selected in the debugger options.
Time: 13.11.2014 03:46:10
Thread:<No Name>[5856]
Here is a Lambda query. The Where filters on a predicate, since Tags is an Array you can use the Any function to perform a search based on another Array-SearchTags. You can store each class object in the Listbox since it stores Objects, you just need to tell it what to display(see below).
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As As String
Public Overrides Function ToString() As String
'to tell the Listbox what to display
Return String.Format("{0} - {1}", Me.Id, String.Join(Me.Tags, " "))
End Function
End Class
Dim searchTags = textbox1.Text.Split(" "c)
Dim query = mainlist.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
Listbox1.Items.Add(et)
Next
Dim suffix As String = "_version"
I have a file called "Something_version1.jpg"
I need to split this so that I get "Something_version"
The following gets me "1.jpg"
filename = filename.Split(New String() {suffix}, StringSplitOptions.None)(1)
And the following gets me "Something"
filename = filename.Split(New String() {suffix}, StringSplitOptions.None)(0)
But what I need is "Something_version"
The suffix is dynamic, and can change.
Hope this is easier than I'm making it.
Thank you.
If you don't care about the "1.jpg" part at all, and all you want is the suffix and the part before the suffix, you can do what you have above (the second one) to get the prefix, and simply concatenate the prefix and suffix to get the answer you're looking for.
The split call might be overkill but it will do the job.
Try this!
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim suffix As String = "_version"
Dim searchThis As String = "something_version1.png"
MsgBox(GetPrefix(suffix, searchThis))
End Sub
Function GetPrefix(suffix As String, searchThis As String) As String
Dim suffixLocation As Integer = searchThis.IndexOf(suffix) + suffix.Count
Return searchThis.Substring(0, suffixLocation)
End Function
End Class
I am trying to find if mylines() contains a value or not. I can get the value by mylines.Contains method:
Dim mylines() As String = IO.File.ReadAllLines(mypath)
If mylines.Contains("food") Then
MsgBox("Value Exist")
End If
But the problem is that I want to check if mylines() contains a line which starts with my value. I can get this value from a single line by mylines(0).StartsWith method. But how do I find a string from all the lines which is starting from some value, e.g. "mysearch" and then get that line number?
I am using a for loop to do so, but it is slow.
For Each line In mylines
If line.StartsWith("food") Then MsgBox(line)
Next
Constrained to code for .NET 2.0, please.
Here's one way with Framework 2.0 code, simply set SearchString with the the string you want to search for:
Imports System.IO
Public Class Form1
Dim SearchString As String = ""
Dim Test() As String = File.ReadAllLines("Test.txt")
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
SearchString = "Food"
End Sub
Private Function StartsWith(s As String) As Boolean
Return s.StartsWith(SearchString)
End Function
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim SubTest() As String = Array.FindAll(Test, AddressOf StartsWith)
ListBox1.Items.AddRange(SubTest)
End Sub
End Class
When I test this with a file with 87,000 lines, it takes about .5 sec, to fill the listbox.
I'm not a VB guy, but I think you could use Linq:
Dim mylines() As String = IO.File.ReadAllLines(mypath)
??? = mylines.Where(Function(s) s.StartWith("food")) //not sure of the return type
Check out: How do I append a 'where' clause using VB.NET and LINQ?