Hoping this would be simple, but doesnt seem to be.
I've got a variable in vb.net 'contactname'.
format is like "John Smith"
I want to get just the forename from this, but cant seem to do it.
I've found and adapted some examples from google, but nothing seems to work :(
Just Split the string on spaces and take the first element:
contactname.Split(" "c)(0)
Could use Regex if you like:
Public Shared Function RegexGetForename(ByVal str As String) As String
Dim a = New System.Text.RegularExpressions.Regex("^(\w+)")
If a.IsMatch(str) Then
Return a.Match(str).Value
Else
Return vbNull
End If
End Function
Dim forename as string
Dim i = contactname.IndexOf(" ")
If i <> -1 Then
forename = contactname.Substring(0, i)
MsgBox(forename)
End If
try it
Related
I am using regex.ismatch to check a string doesn't contain any one of a list of characters such as £&+(/?!;:* And also a quotation mark " not sure how to place that...
But can't get to to work...
If Regex.ismatch(Line, "^[^##£&+()*']"). Then
Msgbox("error")
End If
But doesn't work for me?
Any suggestions
You could do this pretty easily without Regex by simply doing something like this:
Public Shared Function HasSpecialChars(ByVal str As String) As Boolean
Const specialChars As String = "!##$%^&*()"
Dim indexOf As Integer = str.IndexOfAny(specialChars.ToCharArray())
Return indexOf <> -1
End Function
I have a vb.net Project with a Dataset with some Cells with Strings like "JB-Y[ST]Y". My Problem is you can't use datatable.select("Column like 'JB-Y[ST]Y'") because of the brackets (the select thinks this is a pattern, but I need an exact match). Anyone has an idea on this topic? I can't find a solution... Thank you!
I can't find a solution using Regex.Replace so I have a brute force solution like this
Public Function ReplaceBrackets(search as String) As String
Dim sb As StringBuilder = New StringBuilder()
For Each c In search
If c = "[" Then
sb.Append("[[]")
Else if c = "]" Then
sb.Append("[]]")
Else
sb.Append(c)
End If
Next
return sb.ToString()
End Function
And you can call it in your Select statement like this
datatable.Select("Column like '" & ReplaceBrackets(search) & "'")
Does anybody know how to lowercase the first word for each line in a textbox?
Not the first letter, the first word.
I tried like this but it doesn't work:
For Each iz As String In txtCode.Text.Substring(0, txtCode.Text.IndexOf(" "))
iz = LCase(iz)
Next
When you call Substring, it is making a copy of that portion of the string and returning it as a new string object. So, even if you were successfully changing the value of that returned sub-string, it still would not change the original string in the Text property.
However, strings in .NET are immutable reference-types, so when you set iz = ... all you are doing is re-assigning the iz variable to point to yet another new string object. When you set iz, you aren't even touching the value of that copied sub-string to which it previously pointed.
In order to change the value of the text box, you must actually assign a new string value to its Text property, like this:
txtCode.Text = "the new value"
Since that is the case, I would recommend building a new string, using a StringBuilder object, and then, once the modified string is complete, then set the text box's Text property to that new string, for instance:
Dim builder As New StringBuilder()
For Each line As String In txtCode.Text.Split({Environment.NewLine}, StringSplitOptions.None)
' Fix case and append line to builder
Next
txtCode.Text = builder.ToString()
The solutions here are interesting but they are ignoring a fundamental tool of .NET: regular expressions. The solution can be written in one expression:
Dim result = Regex.Replace(txtCode.Text, "^\w+",
Function (match) match.Value.ToLower(), RegexOptions.Multiline)
(This requires the import System.Text.RegularExpressions.)
This solution is likely more efficient than all the other solutions here (It’s definitely more efficient than most), and it’s less code, thus less chance of a bug and easier to understand and to maintain.
The problem with your code is that you are running the loop only on each character of the first word in the whole TextBox text.
This code is looping over each line and takes the first word:
For Each line As String In txtCode.Text.Split(Environment.NewLine)
line = line.Trim().ToLower()
If line.IndexOf(" ") > 0 Then
line = line.Substring(0, line.IndexOf(" ")).Trim()
End If
// do something with 'line' here
Next
Loop through each of the lines of the textbox, splitting all of the words in the line, making sure to .ToLower() the first word:
Dim strResults As String = String.Empty
For Each strLine As String In IO.File.ReadAllText("C:\Test\StackFlow.txt").Split(ControlChars.NewLine)
Dim lstWords As List(Of String) = strLine.Split(" ").ToList()
If Not lstWords Is Nothing Then
strResults += lstWords(0).ToLower()
If lstWords.Count > 1 Then
For intCursor As Integer = 1 To (lstWords.Count - 1)
strResults += " " & lstWords(intCursor)
Next
End If
End If
Next
I used your ideas guys and i made it up to it like this:
For Each line As String In txtCode.Text.Split(Environment.NewLine)
Dim abc() As String = line.Split(" ")
txtCode.Text = txtCode.Text.Replace(abc(0), LCase(abc(0)))
Next
It works like this. Thank you all.
BEFORE:
Johnson0, Yvonne
AFTER:
Johnson, Yvonne
String functions for Access can be found at http://www.techonthenet.com/access/functions/string/replace.php
In your example, code like
Replace("Johnson0", "0", "")
will do the trick for the particular string Johnson0. If you need to only remove the zero if it is the last character, play with the additional start and count parameters described in the link above.
You can try executing following query..
UPDATE table set
columnName = REPLACE(columnName,'0','')
WHERE columnName LIKE "%0%";
This will replace all occurrence of "0" with "".
The answer you submitted clarifies your requirement. Based on that, you don't need to create a user-defined function if your Access version is 2000 or later. You can get the same result with the Replace() function.
MsgBox Replace("Jonson0, Yvonne", "0,", ",")
One approach is to create a custom function
See http://www.techonthenet.com/access/functions/misc/alphanumeric.php for an example. You could do something similar, but in the loop you would only keep the alpha characters.
Public Sub xxx()
MsgBox RemoveStr0("Jonson0, Yvonne")
End Sub
Public Function RemoveStr0(sString As String) As String
Dim ipos As Long, sTemp As String
ipos = InStr(1, sString, "0,")
sTemp = Mid$(sString, 1, ipos - 1)
sTemp = sTemp & Mid$(sString, ipos + 1)
RemoveStr0 = sTemp
End Function
if you can pull it out to java or another OO lang you can just do a matching using regexes.
I'm wondering how I can check if a string contains either "value1" or "value2"?
I tried this:
If strMyString.Contains("Something") Then
End if
This works, but this doesn't:
If strMyString.Contains("Something") or ("Something2") Then
End if
This gives me the error that conversion from string to Long can't be done.
If I put the or ("Something2") inside the parenthesis of the first one, it gives me the error that the string cannot be converted to Boolean.
So how can I check if the string contains either "string1" or "string2" without having to write too much code?
You have to do it like this:
If strMyString.Contains("Something") OrElse strMyString.Contains("Something2") Then
'[Put Code Here]
End if
You need this
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
'Code
End if
In addition to the answers already given it will be quicker if you use OrElse instead of Or because the second test is short circuited. This is especially true if you know that one string is more likely than the other in which case place this first:
If strMyString.Contains("Most Likely To Find") OrElse strMyString.Contains("Less Likely to Find") Then
'Code
End if
Here is the alternative solution to check whether a particular string contains some predefined string. It uses IndexOf Function:
'this is your string
Dim strMyString As String = "aaSomethingbb"
'if your string contains these strings
Dim TargetString1 As String = "Something"
Dim TargetString2 As String = "Something2"
If strMyString.IndexOf(TargetString1) <> -1 Or strMyString.IndexOf(TargetString2) <> -1 Then
End If
NOTE: This solution has been tested with Visual Studio 2010.
You have ("Something2") by itself - you need to test it so a boolean is returned:
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
End if
The error indicates that the compiler thinks you want to do a bitwise OR on a Boolean and a string. Which of course won't work.
If strMyString.Tostring.Contains("Something") or strMyString.Tostring.Contains("Something2") Then
End if
I've approached this in a different way. I've created a function which simply returns true or false..
Usage:
If FieldContains("A;B;C",MyFieldVariable,True|False) then
.. Do Something
End If
Public Function FieldContains(Searchfor As String, SearchField As String, AllowNulls As Boolean) As Boolean
If AllowNulls And Len(SearchField) = 0 Then Return True
For Each strSearchFor As String In Searchfor.Split(";")
If UCase(SearchField) = UCase(strSearchFor) Then
Return True
End If
Next
Return False
End Function
If you want to disregard whether the text is uppercase or lowercase, use this:
If strMyString.ToUpper.Contains("TEXT1") OrElse strMyString.ToUpper.Contains("TEXT2") Then
'Something
End if
Interestingly, this solution can break, but a workaround:
Looking for my database called KeyWorks.accdb which must exist:
Run this:
Dim strDataPath As String = GetSetting("KeyWorks", "dataPath", "01", "") 'get from registry
If Not strDataPath.Contains("KeyWorks.accdb") Then....etc.
If my database is named KeyWorksBB.accdb, the If statement will find this acceptable and exit the If statement because it did indeed find KeyWorks and accdb.
If I surround the If statement qualifier with single quotes like 'KeyWorks.accdb', it now looks for all the consecutive characters in order and would enter the If block because it did not match.