How do I delete characters in a string up to a certain point in classic asp? - asp-classic

I have a string that at any point may or may not contain one or more / characters. I'd like to be able to create a new string based on this string. The new string would include every character after the very last / in the original string.

Sounds like you're wanting the file name from a URL. In any case, it's the same function. The key is using the InStrRev function to find the first / char, but starting from the right. Here's the function:
Function GetFilename(URL)
Dim I
I = InStrRev(URL, "/")
If I > 0 Then
GetFilename = Mid(URL, I + 1)
Else
GetFilename = URL
End If
End Function

Split it up into parts and get the last part:
a = split("my/string/thing", "/")
wscript.echo a(ubound(a))
note: Not safe when the string is empty.

Related

Check to see if file name exists in directory and rename if it does before completing upload?

I am creating a application that allows users to upload an image to the server of my site. But I want to allow users to upload multiple files with the same name by renaming the new file.
But I don't know what methods to use to perform this check.
I am thinking about trying to put all of the filenames into an arraylist individually and creating a loop to check the new filename against the rest and if there is a match then I would randomly generate a string of letters to tag onto the new filename.
But I haven't figured out how to populate the arraylist yet and this is the code I have for checking for repeats against the arraylist:
Dim i As Integer = 0
For i = 0 To arrayFileNames.Count
If (fileName = arrayFileNames(i)) Then
Dim random As Random = New Random()
random.Next(1, 100000)
fileName = fileName & random.ToString
End If
i = i + 1
Next
But this code throws the following error:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Any help would be appreciated, thank you.
If you're creating a For loop, you don't need to manually increase the counter. Remove the line i = i + 1.
Dim i As Integer = 0
For i = 0 To arrayFileNames.Count
If (fileName = arrayFileNames(i)) Then
Dim random As Random = New Random()
random.Next(1, 100000)
fileName = fileName & random.ToString
End If
Next
The for loop already takes care of increasing i.
You'll have a problem if you get a new fileName that is equal to a previous index.
When you create a new instance of random, you'll get the same value.
random.ToString() doesn't return what you think it does (check the output).
You might get a very big filename if you keep appending a big number.
You'll have to change your logic (I haven't tested this code, it's an example to help you out).
Dim random As Random = New Random()
Do While arrayFileNames.Contains(fileName)
fileName = fileName & random.Next(1, 9).ToString
Loop

Asp.Net .Contains all words in any order

I've got a search box which I need to check all words in it against a a string array
So far I've got the following code
For i As Integer = 0 To wordList.Length - 1
If wordList(i).Contains(TextBox1.Text) Then
Dim item As String() = New String(0) {}
item(0) = wordList(i)
items.Add(item)
End If
Next
This checks if the words contain what's in the textbox in the order it is input but not individual words in any order.
Any ideas how I can check every word in any order and only show words from wordList that contain ALL words?
Thanks in advance
Use LINQ:
Dim words As String() = TextBox1.Text.Split(' 'c);
If words.All(AddressOf someString.Contains) Then
If you don't want to match text in the middle, you'll need to use a regex:
If words.All(Function(W) Regex.IsMatch(someString, "\b" + Regex.Escape(w) + "\b"))
try with this code :
result = from item in wordList
where item.Contains(TextBox1.Text)
select item;

Digits Regular Expression Validator

i need a regular expression validation for
numeric digits grouped as X-XXXXX-XXX-X
can any one help?
Regex reg = new Regex("\b[0-9]\-[0-9]{5}\-[0-9]{3}\-[0-9]\b");
Here is what I use for checking social security numbers that user's input:
Public Shared Function CheckSSNFormat(ByVal text As String) As Boolean
Dim digits As String = Regex.Replace(text, "[^0-9]", "")
Return digits.Length = 9
End Function
It doesn't check that they are input in a specific format, but that might be better depending on what you really need -- so just thought I'd give you another option, just incase.
The above just removes everything except digits, and returns true if there are 9 digits (a valid SS#). It does mean some goofy user could enter something like: hello123456789 and it would accept it as valid, but that is fine for me, and I'd rather do that than not accept 123456789 just because I was looking for 123-45-6789 only.
Later I use this to save to my database:
Public Shared Function FormatSSNForSaving(ByVal text As String) As String
If text = "" Then text = "000-00-0000"
Return Regex.Replace(text, "[^0-9]", "")
End Function
and this anytime I want to display the value (actually I use this one for phone numbers, turns out I never display the SS# so don't have a function for it):
Public Shared Function FormatPhoneForDisplay(ByVal text As String) As String
If text.Length <> 10 Then Return text
Return "(" & text.Substring(0, 3) & ") " & text.Substring(3, 3) & "-" & text.Substring(6, 4)
End Function
(^\d{1}-\d{5}-\d{3}-\d{1}$), this should do.
[0-9]-[0-9]{5}-[0-9]{3}-[0-9]
you could also use round brackets to extract the numbers if you want:
([0-9])-([0-9]{5})-([0-9]{3})-([0-9])
and get the values with $1 $2 etc. in the Regex.Replace() function
Regex pattern = new Regex("\b\d-\d{5}-\d{3}-\d\b");
\b - word boundary
\d - digit

How to insert complex strings into Actionscript?

How to insert complex strings into Actionscript?
So I have a string
-vvv -I rc w:// v dv s="60x40" --ut="#scode{vcode=FV1,acode=p3,ab=128,ch=2,rate=4400}:dup{dt=st{ac=http{mime=v/x-flv},mux=mpeg{v},dt=:80/sm.fv}}"
How to insert it into code like
public var SuperPuperComplexString:String = new String();
SuperPuperComplexString = TO_THAT_COMPLEX_STRING;
That string has so many problems like some cart of it can happen to be like regexp BUTI DO NOT want it to be parsed as any kind of reg exp - I need It AS IT IS!)
How to put that strange string into variable (put it not inputing it thru UI - hardcode it into AS code)?
SInce the only problem characters in your string are the double quotes ( " " ), just enclose your String in single quotes ( ' ' ). That will solve any problems.
It also depends on how you are loading that string into your code, as well.
You could even go so far as to encase that String in XML CDATA to ensure it's all delimited for when you want to use it.
var myString:XML = new XML();
myString = "<string><![CDATA[-vvv -I rc w:// v dv s="60x40" --ut="#scode{vcode=FV1,acode=p3,ab=128,ch=2,rate=4400}:dup{dt=st{ac=http{mime=v/x-flv},mux=mpeg{v},dt=:80/sm.fv}}"]]></string>"
Then, you can access it as a string from anywhere by just referencing myString.
var myString:String = '-vvv -I rc w:// v dv s="60x40" --ut="#scode{vcode=FV1,acode=p3,ab=128,ch=2,rate=4400}:dup{dt=st{ac=http{mime=v/x-flv},mux=mpeg{v},dt=:80/sm.fv}}"'
Not sure where your problem is..

Why is this looping infinitely?

So I just got my site kicked off the server today and I think this function is the culprit. Can anyone tell me what the problem is? I can't seem to figure it out:
Public Function CleanText(ByVal str As String) As String
'removes HTML tags and other characters that title tags and descriptions don't like
If Not String.IsNullOrEmpty(str) Then
'mini db of extended tags to get rid of
Dim indexChars() As String = {"<a", "<img", "<input type=""hidden"" name=""tax""", "<input type=""hidden"" name=""handling""", "<span", "<p", "<ul", "<div", "<embed", "<object", "<param"}
For i As Integer = 0 To indexChars.GetUpperBound(0) 'loop through indexchars array
Dim indexOfInput As Integer = 0
Do 'get rid of links
indexOfInput = str.IndexOf(indexChars(i)) 'find instance of indexChar
If indexOfInput <> -1 Then
Dim indexNextLeftBracket As Integer = str.IndexOf("<", indexOfInput) + 1
Dim indexRightBracket As Integer = str.IndexOf(">", indexOfInput) + 1
'check to make sure a right bracket hasn't been left off a tag
If indexNextLeftBracket > indexRightBracket Then 'normal case
str = str.Remove(indexOfInput, indexRightBracket - indexOfInput)
Else
'add the right bracket right before the next left bracket, just remove everything
'in the bad tag
str = str.Insert(indexNextLeftBracket - 1, ">")
indexRightBracket = str.IndexOf(">", indexOfInput) + 1
str = str.Remove(indexOfInput, indexRightBracket - indexOfInput)
End If
End If
Loop Until indexOfInput = -1
Next
End If
Return str
End Function
Wouldn't something like this be simpler? (OK, I know it's not identical to posted code):
public string StripHTMLTags(string text)
{
return Regex.Replace(text, #"<(.|\n)*?>", string.Empty);
}
(Conversion to VB.NET should be trivial!)
Note: if you are running this often, there are two performance improvements you can make to the Regex.
One is to use a pre-compiled expression which requires re-writing slightly.
The second is to use a non-capturing form of the regular expression; .NET regular expressions implement the (?:) syntax, which allows for grouping to be done without incurring the performance penalty of captured text being remembered as a backreference. Using this syntax, the above regular expression could be changed to:
#"<(?:.|\n)*?>"
This line is also wrong:
Dim indexNextLeftBracket As Integer = str.IndexOf("<", indexOfInput) + 1
It's guaranteed to always set indexNextLeftBracket equal to indexOfInput, because at this point the character at the position referred to by indexOfInput is already always a '<'. Do this instead:
Dim indexNextLeftBracket As Integer = str.IndexOf("<", indexOfInput+1) + 1
And also add a clause to the if statement to make sure your string is long enough for that expression.
Finally, as others have said this code will be a beast to maintain, if you can get it working at all. Best to look for another solution, like a regex or even just replacing all '<' with <.
In addition to other good answers, you might read up a little on loop invariants a little bit. The pulling out and putting back stuff to the string you check to terminate your loop should set off all manner of alarm bells. :)
Just a guess, but is this like the culprit?
indexOfInput = str.IndexOf(indexChars(i)) 'find instance of indexChar
Per the Microsoft docs, Return Value -
The index position of value if that string is found, or -1 if it is not. If value is Empty, the return value is 0.
So perhaps indexOfInput is being set to 0?
What happens if your code tries to clean the string <a?
As I read it, it finds the indexChar at position 0, but then indexNextLeftBracket and indexRightBracket both equal 0, you fall into the else condition, and then you insert a ">" at position -1, which will presumably insert at the beginning, giving you the string ><a. The new indexRightBracket then becomes 0, so you delete from position 0 for 0 characters, leaving you with ><a. Then the code finds the <a in the code again, and you're off to the races with an infinite memory-consuming loop.
Even if I'm wrong, you need to get yourself some unit tests to reassure yourself that these edge cases work properly. That should also help you find the actual looping code if I'm off-base.
Generally speaking though, even if you fix this particular bug, it's never going to be very robust. Parsing HTML is hard, and HTML blacklists are always going to have holes. For instance, if I really want to get a <input type="hidden" name="tax" tag in, I'll just write it as <input name="tax" type="hidden" and your code will ignore it. Your better bet is to get an actual HTML parser involved, and to only allow the (very small) subset of tags that you actually want. Or even better, use some other form of markup, and strip all HTML tags (again using a real HTML parser of some description).
I'd have to run it through a real compiler but the mindpiler tells me that the str = str.Remove(indexOfInput, indexRightBracket - indexOfInput) line is re-generating an invalid tag such that when you loop through again it finds the same mistake "fixes" it, tries again, finds the mistake "fixes" it, etc.
FWIW heres a snippet of code that removes unwanted HTML tags from a string (It's in C# but the concept translates)
public static string RemoveTags( string html, params string[] allowList )
{
if( html == null ) return null;
Regex regex = new Regex( #"(?<Tag><(?<TagName>[a-z/]+)\S*?[^<]*?>)",
RegexOptions.Compiled |
RegexOptions.IgnoreCase |
RegexOptions.Multiline );
return regex.Replace(
html,
new MatchEvaluator(
new TagMatchEvaluator( allowList ).Replace ) );
}
MatchEvaluator class
private class TagMatchEvaluator
{
private readonly ArrayList _allowed = null;
public TagMatchEvaluator( string[] allowList )
{
_allowed = new ArrayList( allowList );
}
public string Replace( Match match )
{
if( _allowed.Contains( match.Groups[ "TagName" ].Value ) )
return match.Value;
return "";
}
}
That doesn't seem to work for a simplistic <a<a<a case, or even <a>Test</a>. Did you test this at all?
Personally, I hate string parsing like this - so I'm not going to even try figuring out where your error is. It'd require a debugger, and more headache than I'm willing to put in.

Resources