I want to generate conditional code of the string, which will check the string. An example is the following string
sampleString = "C123 A091 A111 A122 B120 B309 C000"
and examples of conditional string I have is as follows
example 1 :
A123 + B123 would I generate as
if sampleString.contains ("A123") And sampleString.contains ("B123") Then
'doSomething
else
'doSomething
end if
example 2 :
A111+A122+(B120/-C123)
if sampleString.contains ("A111") And sampleString.contains ("A122") And (sampleString.contains ("B120") Or Not sampleString.contains ("C123")) Then
'doSomething
else
'doSomething
end if
Plus (+) means AND
Minus (-) means NOT
Slash (/) means OR
Will I be able to do this in VB.Net?
Use Regex to solve the Contains problem by finding the matches and replace them with 1 or 0.
Dim sample As String = "C123 A091 A111 A122 B120 B309 C000"
Dim input As String = "A111 + A122 + ( B120/- C123)"
Dim nRegex As New Regex("\w+", RegexOptions.IgnoreCase)
Dim nMatches As MatchCollection = nRegex.Matches(input)
For Each nMatch As Match In nMatches
input = input.Replace(nMatch.Value, IIf(sample.Contains(nMatch.Value), "1", "0"))
Next
Now replace the special characters you have with ones that can actually give you the right result when evaluated as a math expression (Since logic is originally math).
input = input.Replace(" ", "")
input = input.Replace("+", "*")
input = input.Replace("/", "+")
input = input.Replace("-1", "0").Replace("-0", "1")
after all this you will get this expression :
1*1*(1+0)
You can now use any math evaluator as suggested in this Answer. If the result you get is bigger than zero means Its logically True. Otherwise False
Related
I have a string. I want to split the string on uneven white spaces. if the white spaces are more or equal to 2 spaces in length than I want them to be in seperate array item, but if there is only one space then I want them to be in same array item so for e.g.
I have this string
1234 This is a Test PASS 1255432 12/21/2016 07:14:11
so when I split the above string, it should be like this
arr(0) = 1234
arr(1) = This is a test ' because it has only one space in between, it there are more or equal to two spaces than I want it to be a seperate item in an array
arr(2) = Pass
arr(3) = 1255432
arr(4) = 12/21/2016
arr(5) = 07:14:1
same thing with below string:
0001 This is a Marketing text_for the students TEST2 468899 12/23/2016 06:23:16
When I split the above string, it should like this:
arr(0)=0001
arr(1) = This is a Marketing text_for the students
arr(2) = Test2
arr(3)=468899
arr(4)=12/23/2016
arr(5) = 06:23:16
Is there any regular expression that can help me to split the string based on spaces, but put together the words if the space is more or equal to 2.
Any help will be greatly appreciated.
This can be done with this regex (\s{0,1}\S+)+ like so:
string text = "0001 This is a Marketing text_for the students TEST2 468899 12/23/2016 06:23:16";
Regex regex = new Regex(#"(\s{0,1}\S+)+");
var matches = regex.Matches("0001 This is a Marketing text_for the students TEST2 468899 12/23/2016 06:23:16").Cast<Match>()
.Select(m => m.Value)
.ToArray();
Console.WriteLine(String.Join( ",", matches));
This is a working java Script snippet of the same thing.
var value = "0001 This is a Marketing text_for the students TEST2 468899 12/23/2016 06:23:16";
var matches = value.match(
new RegExp("(\\s{0,1}\\S+)+", "gi")
);
console.log(matches)
This regex (\s{0,1}\S+)+ works by matching 0 or 1 spaces at the begging of each match with \s{0,1} and then any number of things that aren't a space with \S+ it then matches this whole thing any number of times by containing it in parentheses and using the + operator (...)+, this allows for the string together of single spaces characters.
I am writing this code and have recently come across an error. I have no idea why this is happening. In theory, the english alphabet should be being printed. However, instead of the english alphabet, symbols are being printed instead.
I can not paste the symbols for some reason, but if you ran the code yourself, you'll understand what I mean.
My full code is posted below.
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFHIJKLMNOPQRSTUVWXYZ0123456789"
choice = input("Would you like to encrypt or decrypt? [e/d]: ")
if choice == "e":
message = input("Please insert the message you would like to use: ")
keyword = input("Please insert the keyword you would like to use: ")
ik = len(keyword)
i = 0
string = ''
for A in message:
message1 = (ord(A)) - 96
key1 = (ord(keyword[i])) - 96
addition = message1 + key1
string += (chr(addition))
if i >= ik:
i = 0
else:
i += 1
print (string)
You need to add back the 96 you originally took away :) Alternatively, use the Caesar cipher formula as adding back 96 will still result in symbols appearing (I did the ocr coursework already)
addition = message1 + key1 + 96
your code will not work if the keyword is shorter than the message, so use the modulo operator (%) on i with the length of the keyword inside the line:
key1 = (ord(keyword[i])) - 96
I have this sentense, "The man went outside".
I also have 4 search criterias I would like to get highligted (ignore the brackets), [went|"an WeNT o"|a|t] with [span id="something"][/span].
I have tried out a lot of stuff but I can't figure out how to do this in classic ASP!? If I insert a somewhere in the text, it will search the HTML code for SPAN too, which is bad or it will not find the text as it has been messed up with HTML code. I also tried inserting on all positions in the original text and even with some magic regular expression which I do not understand but I can't get this working :-/
The search-thing is divided with | and can be anything from 1 to 20 things to search for.
Can anyone help me solving how to do this?
I found and tweaked some code and it works perfectly for me:
Function highlightStr (haystack, needles)
' Taken (and tweaked) from these two sites:
' http://forums.aspfree.com/asp-development-5/asp-highlight-keywords-295641.html
' http://www.eggheadcafe.com/forumarchives/scriptingVisualBasicscript/Jul2005/post23377133.asp
'
' INPUT: haystack = search in this string
' INPUT: needles = searches divided by |... example: this|"is a"|search
' OUTPUT: HTML formatted highlighted string
'
If Len(haystack) > 0 Then
' Delete the first and the last array separator "|" (if any)
If Left(needles,1) = "|" Then needles = Right(needles,Len(needles)-1)
If Right(needles,1) = "|" Then needles = Mid(needles,1,Len(needles)-1)
' Delete a multiple seperator (if any)
needles = Replace(needles,"||","|")
' Delete the exact-search chars (if any)
needles = Replace(needles,"""","")
' Escape all special regular expression chars
needles = Replace(needles,"(","\(")
needles = Replace(needles,")","\)")
needles = Replace(needles,".","\.")
If Len(needles) > 0 Then
haystack = " " & haystack & " "
Set re = New RegExp
re.Pattern = "(" & needles & ")"
re.IgnoreCase = True
re.Global = True
highlightStr = re.Replace(haystack,"<span style='background-color:khaki;'>$&</span>")
Else
highlightStr = haystack
End If
Else
highlightStr = haystack
End If
End Function
I'm storing some files in database which has filename like 1839341255115211butterflies.jpg.I need to show this filename to the user as butterflies.jpg.I need to remove the first 16 digit and then show the filename.Added to it I also have few filenames which don't have this 16digit addition prior to the filename.Now my question is how do I identify if this string has 16digit numeric value prior to the filename, based on it remove the 1st 16digit and display just the filename. I'm aware of how to remove the first 16digit and retrive the filename but need help on how to identify a string that has 16digit.
Any suggestion is much appreciated.
A regular expression looks like a good fit here:
^[0-9]{16}
The above will match on strings that start with 16 digits (0 to 9).
Usage:
if(Regex.Match(fileName, #"^[0-9]{16}").Success)
{
fileName = fileName.Remove(0, 16);
}
string.Remove will work quite nicely:
var str = "1839341255115211butterflies.jpg";
str = str.Remove(0, 16);
Console.WriteLine(str);
With Linq:
remove all digits at the beginning until 16 digits:
string file = "1839341255115211butterflies.jpg";
string extension = Path.GetExtension(file);
string fileName = Path.GetFileNameWithoutExtension(file);
fileName = new string(fileName.Where((c, i) => i >= 17 || !Char.IsDigit(c)).ToArray());
file = fileName + extension;
Demo
Edit: If you just want to know if the first 16 chars are digits, it's easier and more readable:
bool startsWith16Digits = file.Take(16).All(Char.IsDigit);
I've to write a csv for a third-party upload. They're saying they can't read the csv file created because it has two extra lines of code and doesn't end (when opened in Notepad) on the last character of the last line. That's true - but can anyone tell me why?
Dim _csvLine As New System.IO.StreamWriter(Server.MapPath("~/folder/_" & rptType.SelectedItem.Value.ToString & ".csv"), False)
Dim tb As New StringBuilder
Dim x As Integer = ds.Tables("csv").Columns.Count, y As Integer = 1
For Each row As Data.DataRow In ds.Tables("csv").Rows
For Each col As Data.DataColumn In ds.Tables("csv").Columns
If y <> x Then
tb.Append(Trim(System.Text.RegularExpressions.Regex.Replace(row.Item(col).ToString, "\s+", " ", RegexOptions.IgnoreCase Or RegexOptions.Multiline)) & ",")
y = y + 1
Else
tb.Append(Trim(System.Text.RegularExpressions.Regex.Replace(row.Item(col).ToString, "\s+", " ", RegexOptions.IgnoreCase Or RegexOptions.Multiline)))
tb.AppendLine()
y = 1
End If
Next
Next
_csvLine.WriteLine(Left(tb.ToString, Len(tb.ToString) - 2))
_csvLine.Flush()
_csvLine.Close()
_csvLine.Dispose()
One line is appended by _csvLine.WriteLine, use Write() instead.
tb.AppendLine() adds the second line, try avoiding it on the last line.
You're doing _csvLine.WriteLine( which is gonna add a linebreak to the end of the file.