How to use Replace function in VBScript - replace

I don't know why this code doesn't work:
Dim a
a = InputBox("What time do you want?")
If InStr(a, "pm") Then
(Replace(a, "pm", ""))
a = a + 12
c = MsgBox(a, 0, Time)
WScript.Quit
Else
End If
b = MsgBox(a & form, 0, "L")
Whenever I try to start it, it responds with:
"Error: Expected Statement"
Is it because the Replace statement isn't right or because there's a mistake in the rest of the script?

When you try to run that code you should get the following error
Microsoft VBScript compilation error: Expected statement
Line 4
which will lead you to the culprit which is
(Replace(a, "pm",""))
which isn't a valid statement in VBScript hence the error.
Based on what you are trying to do the script needs to return the result of the Replace() function call, something like this
a = Replace(a, "pm","")

Related

Casting regex match to String

I created a simple code in Scala that checks whether an input is correctly formatted as HH:mm. I expect the code to result in an Array of valid strings. However, what I'm getting as a result is of type Any = Array(), which is problematic as when I try to print that result I get something like that:
[Ljava.lang.Object;#32a59591.
I guess it's a simple problem but being a Scala newbie I didn't manage to solve it even after a good few hours of googling and trial & error.
val scheduleHours = if (inputScheduleHours == "") {
dbutils.notebook.exit(s"ERROR: Missing param value for schedule hours.")
}
else {
val timePattern = """^((?:[0-30]?[0-9]|2[0-3]):[0-5][0-9])$""".r
val inputScheduleHoursParsed = inputScheduleHours.split(";").map(_.trim)
for (e <- inputScheduleHoursParsed) yield e match {
case timePattern(e) => e.toString
case _ => dbutils.notebook.exit(s"ERROR: Wrong param value for schedule hours: '${inputScheduleHours}'")
}
}
The problem is that some branches return the result you want and others return dbutils.notebook.exit which (I think) returns Unit. Scala must pick a type for the result that is compatible with both Unit and Array[String], and Any is the only one that fits.
One solution is to add a compatible value after the calls to dbutils.notebook.exit, e.g.
val scheduleHours = if (inputScheduleHours == "") {
dbutils.notebook.exit(s"ERROR: Missing param value for schedule hours.")
Array.empty[String]
}
Then all the branches return Array[String] so that will be the type of the result.

Return RegEx MatchCollection from function in VBA - error 450

I have been struggling with this issue for a couple of days and have basically been unable to find a solution
I have written a function in VBA that should return the result from a RegEx.Execute statement but every time the 'End Function' statement is reached, I get a Runtime Error 450 and I simply cannot figure where things go wrong since my assigning of object variables does not throw an error.
I am new to VBA and programming altogether so there is probably just something I have misunderstood in the way objects/MatchCollection/Collections behave.
Here is my code:
Function FindDateAndTimePatternRegEx(s As String) As Object
On Error GoTo erro
Dim objRex As RegExp
Dim arrMatch As Object
's = " Afgår 01-01-2017 00:24:00, anvendt log 01-01-2017 10:53:24 er 10:29:24 EFTER dette"
Set objRex = New RegExp
With objRex
.IgnoreCase = True
.Global = True ' the global parameter makes sure that all pattern matches in the string are found and returned in the return collection
.Pattern = "([0-9]{2}\-[0-9]{2}\-[0-9]{4})" & " " & "([0-9]{2}:[0-9]{2}:[0-9]{2})"
End With
Set arrMatch = objRex.Execute(s)
Set FindDateAndTimePatternRegEx = arrMatch
'Debug.Print FindDateAndTimePatternRegEx.Item(0).FirstIndex
'Debug.Print FindDateAndTimePatternRegEx.Item(1)
Set objRex = Nothing
Exit Function
erro:
MsgBox Err.Description
End Function
Everytime I try this out in the Immediate window calling the function and using the string s
? ?FindDateAndTimePatternRegEx(" Afgår 01-01-2017 00:24:00, anvendt log 01-01-2017 10:53:24 er 10:29:24 EFTER dette")
the debug.print returns the expected values but when either Exit Function or End Function is reached, I get the runtime error 450
Could anybody explain what goes wrong?
Thanks in advance
Best regards
Your regex related code is alright, but the way you are calling the function is wrong: you need to use Set:
Dim regexResults As Object
Set regexResults = FindDateAndTimePatternRegEx(" Afgar 01-01-2017 00:24:00, anvendt log 01-01-2017 10:53:24 er 10:29:24 EFTER dette")
You have to check if the Execute could find something.
Dim i As Integer
If arrMatch.Count = 0 Then
Debug.Print "No match"
Else
For i = 0 To FindDateAndTimePatternRegEx.Count - 1
Debug.Print i; FindDateAndTimePatternRegEx.Item(i).FirstIndex
Next i
End If

Scala regular expression : matching a long unicode Devanagari pattern fails

Consider the following script code:
import scala.util.matching.Regex
val VIRAMA = "्"
val consonantNonVowelPattern = s"(म|त|य)([^$VIRAMA])".r
// val consonantNonVowelPattern = s"(थ|ठ|छ|स|ब|घ|ण|ट|ज|ग|न|ष|भ|ळ|ढ|ख|श|प|ह|ध|ङ|म|झ|ड|ल|व|र|फ|क|द|च|ञ|त|य)([^$VIRAMA])".r
var output = "असय रामः "
output = consonantNonVowelPattern.replaceAllIn(output, _ match {
case consonantNonVowelPattern(consonant, followingCharacter) =>
consonant + VIRAMA + "a" + followingCharacter
})
println("After virAma addition: " + output.mkString("-"))
It produces the following correct output:
After virAma addition: अ-स-य-्-a- -र-ा-म-्-a-ः-
However, if I use the longer pattern (commented out above), I get the following wrong output:
After virAma addition: अ-स-्-a-य- -र-्-a-ा-म-्-a-ः-
Is this a bug? Am I doing something wrong?
The below is thanks to Lalit Pant-
I'm assuming that the correct output for the second case is:
अ-स-्-a-य-्-a- -र-्-a-ा-म-्-a-ः-
If that's the case, read on. If not, tell me the expected output.
The problem appears to be that with your bigger 'consonantNonVowelPattern', the presence of 'सय' in 'output' makes 'य' show up as a 'followingCharacter' in your pattern match after the 'स' consonant.  'य' is consequently never reported as a consonant.

Jasper Report If Else Condition Expression

I would like to ask about the if else expression in ireport jasper report. May I know is it possible to have multiple or more parameter in the if else statement?
(($P{endDate}.isEmpty()==true || $P{endDate}.equals(""))? "" :
" createDate>='" + $P{startDate} +"'" && " createDate<='" + $P{endDate} +"'")
Based on the code above, there are not allowed me to use "&&". It prompt out syntax error.
Besides that, May I know any solution to solve it? Thank you very much.
I'm assuming it's a query expression your trying to write. You probably would have to do something as follows:
Create a parameter for your dataset. This parameter should not be "prompted" and lets call it DATE_LIMIT_EXPRESSION. You should then set its default value as your expression. For example (if I a get what you meant), this could be your default expression:
"1" +
(($P{startDate}.isEmpty() == false) ? (" AND createDate >= " + $P{startDate}) : "") +
(($P{stopDate}.isEmpty() == false) ? (" AND stopDate <= " + $P{stopDate}) : "")
Now, your dataset query should be something like:
select
...
where $P!{DATE_LIMIT_EXPRESSION}
Just notice the "$P!" syntax. You can find more information about this in the Jasper Reports' documentation.

How to do a single line If statement in VBScript for Classic-ASP?

The "single line if statement" exists in C# and VB.NET as in many other programming and script languages in the following format
lunchLocation = (dayOfTheWeek == "Tuesday") ? "Fuddruckers" : "Food Court";
does anyone know if there is even in VBScript and what's the extact syntax?
The conditional ternary operator doesn't exist out of the box, but it's pretty easy to create your own version in VBScript:
Function IIf(bClause, sTrue, sFalse)
If CBool(bClause) Then
IIf = sTrue
Else
IIf = sFalse
End If
End Function
You can then use this, as per your example:
lunchLocation = IIf(dayOfTheWeek = "Tuesday", "Fuddruckers", "Food Court")
The advantage of this over using a single line If/Then/Else is that it can be directly concatenated with other strings. Using If/Then/Else on a single line must be the only statement on that line.
There is no error checking on this, and the function expects a well formed expression that can be evaluated to a boolean passed in as the clause. For a more complicated and comprehensive answer see below. Hopefully this simple response neatly demonstrates the logic behind the answer though.
It's also worth noting that unlike a real ternary operator, both the sTrue and sFalse parameters will be evaluated regardless of the value of bClause. This is fine if you use it with strings as in the question, but be very careful if you pass in functions as the second and third parameters!
VBScript does not have any ternary operator.
A close solution in a single line and without using a user defined function, pure VBScript:
If dayOfTheWeek = "Tuesday" Then lunchLocation = "Fuddruckers" Else lunchLocation = "Food Court"
BTW, you can use JScript in Classic ASP if ternary opertor is so important to you.
edited 2017/01/28 to adapt to some of the non boolean condition arguments
Note: If all you need is to select an string based on an boolean value, please, use the code in the Polinominal's answer. It is simpler and faster than the code in this answer.
For a simple but more "flexible" solution, this code (the original code in this answer) should handle the usual basic scenarios
Function IIf( Expression, TruePart, FalsePart)
Dim bExpression
bExpression = False
On Error Resume Next
bExpression = CBool( Expression )
On Error Goto 0
If bExpression Then
If IsObject(TruePart) Then
Set IIf = TruePart
Else
IIf = TruePart
End If
Else
If IsObject(FalsePart) Then
Set IIf = FalsePart
Else
IIf = FalsePart
End If
End If
End Function
If uses the Cbool function to try to convert the passed Expression argument to a boolean, and accepts any type of value in the TrueValue and FalseValue arguments. For general usage this is fast, safe and fully complies to documented VBScript behaviour.
The only "problem" with this code is that the behaviour of the CBool is not fully "intuitive" for some data types, at least for those of us that constantly change between vbscript and javascript. While numeric values are coherent (a 0 is a False and any other numeric value is a True), non numeric types generate a runtime error (in previous code handled as false), except if it is a string with numeric content or that can be interpreted as true or false value in english or in the OS locale.
If you need it, a VBScript version "equivalent" to the ? javascript ternary operator is
Function IIf( Expression, TruePart, FalsePart )
Dim vType, bExpression
vType = VarType( Expression )
Select Case vType
Case vbBoolean : bExpression = Expression
Case vbString : bExpression = Len( Expression ) > 0
Case vbEmpty, vbNull, vbError : bExpression = False
Case vbObject : bExpression = Not (Expression Is Nothing)
Case vbDate, vbDataObject : bExpression = True
Case Else
If vType > 8192 Then
bExpression = True
Else
bExpression = False
On Error Resume Next
bExpression = CBool( Expression )
On Error Goto 0
End If
End Select
If bExpression Then
If IsObject( TruePart ) Then
Set IIf = TruePart
Else
IIf = TruePart
End If
Else
If IsObject( FalsePart ) Then
Set IIf = FalsePart
Else
IIf = FalsePart
End If
End If
End Function
BUT independently of the version used, be careful, you are calling a function, not using a ternary operator. Any code, or function call you put in TruePart of FalsePart WILL BE EXECUTED independently of the value of the condition. So this code
value = IIf( 2 > 3 , DoSomething(), DontDoSomething() )
WILL EXECUTE the two functions. Only the correct value will be returned to value var.
There's a weird trick possible (hi, Python!) for exact one-liner:
lunchLocation = array("Food Court", "Fuddruckers")(-(dayOfTheWeek = "Tuesday"))
The "magic" works because of a boolean operation specifics in VBScript.
True is actually -1 and False is 0, therefore we can use it as an index for array (just get rid of a minus). Then the first item of array will be a value for False condition and second item for True.
related to #MC_ND answer:
to execute only one function, you can do something like that:
If VarType(TruePart) = vbString and InStr(1,TruePart,"function:") = 1 then
IIf = GetRef(Mid(TruePart,10))()
Else
IIf = TruePart
End If
the same for the FalsePart, and call IIf() it like that:
value = IIf( 2 > 3 , "function:DoSomething", "function:DontDoSomething" )
and will call DoSomething() or DontDoSomething()