is there a way in vb.net that i can run an if statement to say if a variable starts with 07 then between 1-9
i know i could do this using substring which would work but it would make the if statement rather large
number_called.Substring(0, 3) = "071" or number_called.Substring(0, 3) = "072"
and so on up to 079 but can i create a shorter if statement for the whole range?
This would do it
Private Function CheckNumber(myNumber As String) As Boolean
Dim regex As Regex = New Regex("^07[1-9]]")
Dim match As Match = regex.Match(myNumber)
Return match.Success
End Function
Just call CheckNumber("071") or CheckNumber(number_called)
Remember to import the references Imports System.Text.RegularExpressions
Updated Expression, thank you Veeke
You could use String.StartsWith("07") and check the last character of the String - it must be a number and not 0 like this:
If str.Length = 3 And str.StartsWith("07") And Char.IsNumber(str(2)) And str(2) <> "0" Then
End If
If you know that it will always start with 3 numbers you can parse it
Dim num = Int32.Parse(number_called.Substring(0, 3))
Dim Valid= num>69 and num<80
If you dont know if it will start with 3 numbers, surround it with a TryCatch
Small correction on Malcor's post, which doesn't check if it begins with '07' (just if it contains '07'):
Private Function CheckNumber(myNumber As String) As Boolean
Dim regex As Regex = New Regex("^07[1-9]")
Dim match As Match = regex.Match(myNumber)
Return match.Success
End Function
You could use StartsWith coupled with a Select Case if you are sure it is always a numeric string:
If number_called.StartsWith("07") Then
Select Case CInt(number_called.SubString(2, 1))
Case 1 to 9
'it matched
Case Else
'it didn't match
End Select
End If
Related
I have a string ABC(N9KGRTLMN9(0J)M3.
I want to return the character after GRTLM which is N. Thanks.
Look at the System.Text.RegularExpressions namespace, and create a RegEx object with this expression:
GRTLM(.)
Then you will be able to check the Matches for the expression to find your character. Depending on what you know about that string, you may be able to narrow things even further. For example:
GRTLM([A-Za-z])
or
GRTLM([A-Z])
If you don't want to use regular expressions (for any reason), here's an alternative:
Private Function ReturnCharAfter(Source As String, after As String) As Char
Dim i As Integer = Source.IndexOf(after)
If i < 0 Then Return Nothing
Return Source(i + after.Length)
End Function
usage:
Dim N As Char = ReturnCharAfter("ABC(N9KGRTLMN9(0J)M3.", "GRTLM")
You could use String.Split() to get the N
Dim input = "ABC(N9KGRTLMN9(0J)M3"
Dim s = "GRTLM"
Dim n = input.Split({s}, StringSplitOptions.RemoveEmptyEntries)(1)(0)
It splits the string into substrings using GRTLM as a delimiter, then returns the first character of the second array item.
Or to get the index of N
Dim i = input.Split({s}, StringSplitOptions.RemoveEmptyEntries)(0).Length + s.Length
It splits the string and returns the length of the first array item plus the length of the delimiter string.
But perhaps the simplest way to do it is using String.IndexOf()
Dim n = input(input.IndexOf(s) + s.Length)
Dim i = input.IndexOf(s) + s.Length
I have the following string expression:
str="1+2+3+4"
Now from this string I want the value of number (10). How can I get this value from this expression?
For that to work, you'd have to parse all the numbers, something like this
Dim str As String= "1+2+3+4"
Dim numbers() As String = str.Split('+')
Dim result As Integer = 0
For Each number As String In numbers
result += Integer.Parse(number)
Next
Here is an alternative solution that uses Linq. This solution excludes nothing it can not parse...
YOURSTRING.Split("+").ToList.Where(Function(sr) Not String.IsNullOrEmpty(sr) AndAlso Integer.TryParse(sr, New Integer)).Sum(Function(s As String) Integer.Parse(s))
Example Output
1+2+3+4 = 10
1+2+3+4++12+1 = 23 (Notice the typo (4++12), it still works even it there's a mistake)
Suppose I want to use an If statement, but I won't know until run-time what the actual condition of the If statement will be. Is there a way to do this by passing the condition as the contents of a string? As an example of the kind of thing I'm looking to acheive, consider the following bit of code;
Dim a as Integer = 1
Dim b as Integer = 2
Dim ConditionString As String = "<"
If a ConditionString b Then
...
End If
Mainly what I'm looking for is some way to leave the actual condition undefined until run-time. The reason I want to do this is because I need to have a set of threshold conditions in a database including not just the numeric values themselves, but also comparison operations. I might want to have something that amounts to "> 3.2 And < 5.6". As numbers are pulled in from data, the comparison operations need to be applied to the data depending on various conditions. Also, the database would be changed from time-to-time.
For such cases I love to use NCalc library, it has everything you need - it parses simple expressions (including logical and relational). Here is an example of it in C#:
var expr = new Expression("[X] > 3.2 and [X] < 5.6");
expr.Parameters["X"] = 10.0;
if (expr.Evaluate())
{
// ...
}
and VB.NET:
Dim expr As var = New Expression("[X] > 3.2 and [X] < 5.6")
expr.Parameters("X") = 10
If expr.Evaluate Then
' ...
End If
You can store a map of String to Func(Of Integer, Integer, Boolean) keyed by the strings "<", ">", "==", and so on, and take addresses of the functions that implement those conditions. For example:
Function LessThan(Integer a, Integer b) As Boolean
Return a < b
End Function
Dim Comparisons As New Map(Of String, Func(Of Integer, Integer, Boolean))
Comparisons.Add("<", AddressOf LessThan)
And then you can call it as such:
Dim a as Integer = 1
Dim b as Integer = 2
Dim ConditionString As String = "<"
If Comparisons(ConditionString)(a, b) Then
There are only a few possible conditions so I would just use a Select..Case statement:
Select Case ConditionString
Case "<"
Case ">"
'etc.
Case Else
End Select
Otherwise, you cannot (simply) convert a string "<" to an operator.
You just need a 'code', mapping some kind of value that you can store in a database to the various kinds of "conditions" you wish to test. Instead of a string, I'd suggest using an enum:
Enum ConditionEnum
LessThan
GreaterThan
Equal
SomeOtherVeryComplicatedBinaryFunction
End Enum
And then define a method that evaluates the condition along with the two arguments:
Public Sub EvaluateConditionWithArguments(ConditionEnum condition, Integer a, Integer b) As Boolean
EvaluateConditionWithArguments = False
Select Case condition
Case ConditionEnum.LessThan
If a < b Then
EvaluateConditionWithArguments = True
End If
...
End Select
End Sub
In an MS Access 2007 project report, I have the following (redacted) query:
SELECT SomeCol FROM SomeTable
The problem is, that SomeCol apparently contains some invisible characters. For example, I see one result returned as 123456 but SELECT LEN(SomeCol) returns 7. When I copy the result to Notepad++, it shows as ?123456.
The column is set to TEXT. I have no control over this data type, so I can't change it.
How can I modify my SELECT query to strip out anything non-numeric. I suspect RegEx is the way to go... alternatively, is there a CAST or CONVERT function?
You mentioned using a regular expression for this. It is true that Access' db engine doesn't support regular expressions directly. However, it seems you are willing to use a VBA user-defined function in your query ... and a UDF can use a regular expression approach. That approach should be simple, easy, and faster performing than iterating through each character of the input string and storing only those characters you want to keep in a new output string.
Public Function OnlyDigits(ByVal pInput As String) As String
Static objRegExp As Object
If objRegExp Is Nothing Then
Set objRegExp = CreateObject("VBScript.RegExp")
With objRegExp
.Global = True
.Pattern = "[^\d]"
End With
End If
OnlyDigits = objRegExp.Replace(pInput, vbNullString)
End Function
Here is an example of that function in the Immediate window with "x" characters as proxies for your invisible characters. (Any characters not included in the "digits" character class will be discarded.)
? OnlyDigits("x1x23x")
123
If that is the output you want, just use the function in your query.
SELECT OnlyDigits(SomeCol) FROM SomeTable;
There is no RegEx in Access, at least not in SQL. If you venture to VBA, you might as well use a custom StripNonNumeric VBA function in the SQL statement.
e.g. SELECT StripNonNumeric(SomeCol) as SomeCol from SomeTable
Function StripNonNumeric(str)
keep = "0123456789"
outstr = ""
For i = 1 to len(str)
strChar = mid(str,i,1)
If instr(keep,strChar) Then
outstr = outstr & strChar
End If
Next
StripNonNumeric = outstr
End Function
You can do it all in a query, combining this question with your previous question, you get:
SELECT IIf(IsNumeric([atext]),
IIf(Len([atext])<4,Format([atext],"000"),
Replace(Format(Val([atext]),"#,###"),",",".")),
IIf(Len(Mid([atext],2))<4,Format(Mid([atext],2),"000"),
Replace(Format(Val(Mid([atext],2)),"#,###"),",","."))) AS FmtNumber
FROM Table AS t;
Public Function fExtractNumeric(strInput) As String
' Returns the numeric characters within a string in
' sequence in which they are found within the string
Dim strResult As String, strCh As String
Dim intI As Integer
If Not IsNull(strInput) Then
For intI = 1 To Len(strInput)
strCh = Mid(strInput, intI, 1)
Select Case strCh
Case "0" To "9"
strResult = strResult & strCh
Case Else
End Select
Next intI
End If
fExtractNumeric = strResult
End Function
i need to get a set of values after certain 14 length of a string and before the last 5 stringss.
eg:
Theboyisgoingt9123holdi: so i need to get the value 9123
iamfullofmeats89holdi: i need to extract value 89
so the algorithm here is, i am trying to extract the values that comes after the 14th length of the string and just before the last 5 characters of the same string.
its always whats between 14th and last 5 characters.
i am coding in vb.net.
any ideas is great appreciated.
Dim ResultString As String
ResultString = Regex.Match(SubjectString, "(?<=^.{14}).*(?=.{5}$)").Value
will give you the characters from the 15th until the 6th-to-last character in the string. It is assumed that there are no newlines in the string. If there are, and you want to treat them just like any other character, use the option RegexOptions.Singleline as an additional parameter to Regex.Match().
Explanation:
(?<=^.{14}): Match a position that is after the 14th character in the string.
.*: Match anything until...
(?=.{5}$): ...the position before the last 5 characters in the string.
I too would go with a regex. This is how I would do it:
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim str As String = "Theboyisgoingt9123holdi"
Dim m As Match = Regex.Match(str, "^.{14}(.+).{5}$")
If m.Success Then
Console.WriteLine(m.Groups(1).Value)
End If
End Sub
End Module
This is a great place to use a regular expression
Function GetNumber(ByVal str As String) As String
Dim match = Regex.Match("\d+", str)
if math.Sucess then
Return match.Value
Else
Return String.Empty
End If
End Function