I have an issue trimming a string in vb.net
Dim bgColor1 As String = (foundRows(count).Item(16).ToString())
'This returns Color [Indigo] I need it to be just Indigo so vb.net can read it.
'So i used this
Dim MyChar() As Char = {"C", "o", "l", "r", "[", "]", " "}
Dim firstBgcolorbgColor1 As String = bgColor1.TrimStart(MyChar)
'But the ] is still in the string so it looks like this Indigo]
Any ideas on why i cannot trim the ]?
Update
Didn't see that the input was "Color [Indigo]". I would not recommend TrimStart() & TrimEnd()
You have a variety of options to choose from:
Imports System
Imports System.Text.RegularExpressions
Public Module Module1
Public Sub Main()
Dim Color As String = "Color [Indigo]"
' Substring() & IndexOf()
Dim openBracket = Color.IndexOf("[") + 1
Dim closeBracket = Color.IndexOf("]")
Console.WriteLine(Color.Substring(openBracket, closeBracket - openBracket))
' Replace()
Console.WriteLine(Color.Replace("Color [", String.Empty).Replace("]", String.Empty))
' Regex.Replace()
Console.WriteLine(Regex.Replace(Color, "Color \[|\]", String.Empty))
' Regex.Match()
Console.WriteLine(Regex.Match(Color, "\[(\w+)\]").Groups(1))
End Sub
End Module
Results:
Indigo
Indigo
Indigo
Indigo
Demo
Well, you are calling TrimStart(...), which as the name implies, will only trim the front part of the string.
Did you mean to call Trim(MyChar) instead?
You could use a Regex to do the job:
Dim colorRegex As New Regex("(?<=\[)\w+") 'Get the word following the bracket ([)
Dim firstBgcolorbgColor1 As String = colorRegex.Match(bgColor1).Value
The TrimStart, TrimEnd, and Trim functions remove spaces from beginning, end and both side of the strings respectively. You are using TrimStart to remove any leading the spaces but it is leaving white space is at the end. So you need to use Trim. Trim won't remove anything else than white space characters, so your ] character will still appear in the final string. You need to do String.Remove to remove characters you don't want.
Examples here: http://www.dotnetperls.com/remove-vbnet
Related
I wish to remove spaces from lines that doesn't contain text, but not remove the line. Since a space character can be hard to identify, I will replace the space character with the "#" (hastag character) to showcase the example easier. The string looks something like this:
"This is
########a long string
with many lines
#######
and the above is empty
####this is empty
#############
#######hello"
I wish that the output would remove the spaces on the lines that only contains the space character. I am still using the "#" (hastag character) to showcase the spaces. The final output should look like this:
"This is
########a long string
with many lines
and the above is empty
####this is empty
#######hello"
Without the hashtag character acting as the space character, the expected output should look like this:
"This is
a long string
with many lines
and the above is empty
this is empty
hello"
So to fully clarify, I wish to remove space characters on a line that doesn't contain text, but not remove the line.
Using your example with octothorpes (yet another name for #) and replacing them with spaces in the code, we can use the String.IsNullOrWhiteSpace function to check for such lines and replace them with empty strings:
Module Module1
Sub Main()
Dim s = "This is
########a long string
with many lines
#######
and the above is empty
####this is empty
#############
#######hello"
s = s.Replace("#", " ")
Dim t = String.Join(vbCrLf, s.Split({vbCrLf}, StringSplitOptions.None).
Select(Function(a) If(String.IsNullOrWhiteSpace(a), "", a)))
Console.WriteLine(t)
Console.ReadLine()
End Sub
End Module
Outputs:
This is
a long string
with many lines
and the above is empty
this is empty
hello
Use the following code:
Dim container As String = IO.File.ReadAllText("test.txt")
container = container.Replace(vbNewLine, vbCr).Replace(vbLf, vbCr)
Do While container.Contains(vbCr & vbCr)
container = container.Replace(vbCr & vbCr, vbCr)
Loop
If container.StartsWith(vbCr) Then container = container.TrimStart(Chr(13))
container = container.Replace(vbCr, vbNewLine)
IO.File.WriteAllText("test.txt", container)
It'll trim all the empty new lines and override the file (before vs. after):
Note: If you want to remove the hashes and replace that with white spaces too, just use the following:
Dim container2 As String =
My.Computer.FileSystem.ReadAllText("test.txt").Replace("#", " ")
IO.File.WriteAllText("test.txt", container2)
Try this
Dim myString = "your multiline string here"
Dim finalString As String
For each line In myString.Split(CChar(vbNewLine))
finalstring &= line.Trim() & vbNewLine
Next
I have inserted a option in Dorpdown as follows
<option>إختر </option>
When I select this text from server side on any event I get this value
"إختر "
Now I want to replace this white space in the string. I have tried replace method of String class. But its not working.
str = str.replace(" ","")
Plz suggest
What you should do first is decode the HTML, such that text like but also & are converted to their textual counterparts (" " and "&"). You can do this with: WebUtility.HtmlDecode. Next you can use String.Trim to remove leading and tailing spaces.
Example:
string s = "إختر ";
string r = WebUtility.HtmlDecode(s).Trim();
Or the VB.NET equivalent:
Dim s As String = "إختر "
Dim r As String = WebUtility.HtmlDecode(s).Trim()
Evidently you can try to convert to spaces yourself. But there are examples where it is not that evident and your transcoder can get confused or decode strings the wrong way. Furthermore if in the future the people at W3C change their minds about how to encode text in HTML/XML, then your program will still work.
String.Trim will remove all kinds of white-space including spaces, new lines, tabs, carriage returns, etc. If you only want to remove spaces, you can use: .Trim(' '). Then you specify only to remove the given list of characters (here only ' ').
If you want to remove leading or trailing white-spaces from a string you just need to use String.Trim, but you have to re-assign the return value to the variable since strings are immutable:
string text = "إختر ";
text = text.Trim();
Note that you can also use TrimEnd in this case.
If you want to remove only space characters(not also tabs or new-line characters which are also white-spaces) use:
text = text.Trim(' ');
If you instead want to remove all spaces from a string you could do:
text = text.Replace(" ", "");
I think maybe your code is something like this
Dim str As String = "إختر "
str.Replace(" ", "")
But actually you should
Dim str As String = "إختر "
str = str.Replace(" ", "")
I have just had a similar problem.
It turns out, that this nbsp character is Chr(160) from the ASCII table. Thus, something like this is quite meaningful, for all the cases. It works, on a selected area:
Public Sub remove_space_in_string()
Dim r_range As Range
For Each r_range In Selection
r_range = Trim(r_range)
r_range = Replace(r_range, vbTab, "")
r_range = Replace(r_range, " ", "")
r_range = Replace(r_range, Chr(160), "")
Next r_range
End Sub
Let me say, I hate working with strings! I'm trying to find a way to split a string on brackets. For example, the string is:
Hello (this is) me!
And, from this string, get an array with Hello and me. I would like to do this with parentheses and braces (not with brackets). Please note that the string is variable, so something like SubString wouldn't work.
Thanks in advance,
FWhite
You can use regular expressions (Regex), below code should exclude text inside all parenthesis and braces, also removes an exclamation mark - feel free to expand CleanUp method to filter out other punctuation symbols:
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim re As New Regex("\(.*\)|{.*}") 'anything inside parenthesis OR braces
Dim input As String = "Hello (this is) me and {that is} him!"
Dim inputParsed As String = re.Replace(input, String.Empty)
Dim reSplit As New Regex("\b") 'split by word boundary
Dim output() As String = CleanUp(reSplit.Split(inputParsed))
'output = {"Hello", "me", "and", "him"}
End Sub
Private Function CleanUp(output As String()) As String()
Dim outputFiltered As New List(Of String)
For Each v As String In output
If String.IsNullOrWhiteSpace(v) Then Continue For 'remove spaces
If v = "!" Then Continue For 'remove punctuation, feel free to expand
outputFiltered.Add(v)
Next
Return outputFiltered.ToArray
End Function
End Module
To explain the regular expression I used (\(.*\)|{.*}):
\( is just a (, parenthesis is a special symbol in Regex, needs to be escaped with a \.
.* means anything, i.e. literally any combination of characters.
| is a logical OR, so the expression will match either left or ride side of it.
{ does not need escaping, so it just goes as is.
Overall, you can read this as Find anything inside parenthesis or braces, then the code says replace the findings with an empty string, i.e. remove all occurrences. One of the interesting concepts here is understanding greedy vs lazy matching. In this particular case greedy (default) works well, but it's good to know other options.
Useful resources for working with Regex:
http://regex101.com/ - Regex test/practice/sandbox.
http://www.regular-expressions.info/ - Theory and examples.
http://www.regular-expressions.info/wordboundaries.html - How word boundaries work.
Try this code:
Dim var As String = "Hello ( me!"
Dim arr() As String = var.Split("(")
MsgBox(arr(0)) 'Display Hello
MsgBox(arr(1)) 'Display me!
Something like this should work for you:
Dim x As String = "Hello (this is) me"
Dim firstString As String = x.Substring(0, x.IndexOf("("))
Dim secondString As String = x.Substring(x.IndexOf(")") + 1)
Dim finalString = firstString & secondString
x = "Hello (this is) me"
firstString = "Hello "
secondString = " me"
finalString = "Hello me"
I want to filter out other characters from a string as well as split the remaining numbers with periods.
This is my string: major.number=9minor.number=10revision.number=0build.number=804
and this is the expected output: 9.10.0.804
Any suggestions?
As to my comment, if your text is going to be constant you can use String.Split to remove the text and String.Join to add your deliminators. Quick example using your string.
Sub Main()
Dim value As String = "major.number=9minor.number=10revision.number=0build.number=804"
Dim seperator() As String = {"major.number=", "minor.number=", "revision.number=", "build.number="}
Console.WriteLine(String.Join(".", value.Split(seperator, StringSplitOptions.RemoveEmptyEntries)))
Console.ReadLine()
End Sub
If your string does not always follow a specific pattern, you could use Regex.Replace:
Sub Main()
Dim value as String = "major.number=9minor.number=10revision.number=0build.number=804"
Dim version as String = Regex.Replace(value, "\D*(\d+)\D*", "$1.") ' Run the regex
version = version.Substring(0, version.Length - 1) ' Trim the last dot
End
Note you should Imports System.Text.RegularExpressions.
These are valid characters:
a-z
A-Z
0-9
-
/
How do I remove all other characters from my string?
Dim cleanString As String = Regex.Replace(yourString, "[^A-Za-z0-9\-/]", "")
Use either regex or Char class functions like IsControl(), IsDigit() etc. Get a list of these functions here: http://msdn.microsoft.com/en-us/library/system.char_members.aspx
Here's a sample regex example:
(Import this before using RegEx)
Imports System.Text.RegularExpressions
In your function, write this
Regex.Replace(strIn, "[^\w\\-]", "")
This statement will replace any character that is not a word, \ or -. For e.g. aa-b#c will become aa-bc.
Dim txt As String
txt = Regex.Replace(txt, "[^a-zA-Z 0-9-/-]", "")
Function RemoveCharacter(ByVal stringToCleanUp)
Dim characterToRemove As String = ""
characterToRemove = Chr(34) + "#$%&'()*+,-./\~"
Dim firstThree As Char() = characterToRemove.Take(16).ToArray()
For index = 1 To firstThree.Length - 1
stringToCleanUp = stringToCleanUp.ToString.Replace(firstThree(index), "")
Next
Return stringToCleanUp
End Function
I've used the first solution from LukeH, but then realized that this code replaces the dot for extension, therefore I've just upgraded the code slightly:
Dim fileNameNoExtension As String = Path.GetFileNameWithoutExtension(fileNameWithExtension)
Dim cleanFileName As String = Regex.Replace(fileNameNoExtension, "[^A-Za-z0-9\-/]", "") & Path.GetExtension(fileNameWithExtension)
cleanFileName will the file name with no special characters with extension.