Let say i have a string like this 'this is a statement'
and if i want to search and replace string with this 'this ** a statement'
string to search for this is a statement , this si a statement , this i a statement and any combination convert them into this trim a statement
i.e for any word combination between this & a statement replace it with trim
for another set replace fun to notfun .
so this is the program
import re
file=open('file','r+')
search=re.sub('this \(a_zA_Z0_9)+ a statement','\1trim',file),('this is fun','this is notfun',file)
file.close()
something is not right as nothing is getting changed in the file.
thanks everyone.
re.sub doesn't work on files, it works on strings. You need to read the contents of the file into a string, then use re.sub to change the string, then write the modified string back to the file.
A simple example:
text = open("myfile.txt").read()
# This is your original re.sub call, but I'm not sure it really does what you want.
text = re.sub('this \(a_zA_Z0_9)+ a statement', '\1trim', text)
text = re.sub('this \(a_zA_Z0_9)+ another replacement', 'some other thing', text)
open("myfile.txt", "w").write(text)
Related
First of all I have little to no knowledge about VBA.. probably none at all. However I was asked to create a VBA program that paste text from clipboard in different cells. My text has the following format:
seminar: name of Seminar (in cell(1,1))
first name: participant's first name (in cell(1,2))
last name: participant's last name (in cell(1,3)) etc..
So far I was able to read the text from clipboard. Then I found the position of the ":" in order to paste only what is AFTER it in the cell.
At this point I thought to find the position of the RETURN character in order to know where the first line ends(ex. "name of Seminar") with this line of code which I found online:
end_str = InStr(str, vbCrLf) - 1
and with the Right (string, length) function to get the relative text.
This is not working. I think because there are not return character in the string variable that holds the data? I don't know.
My question is: Is it possible to check the RETURN character somehow or Is there a better way to create this program?
Thank you in advance.
An easy way would be to use the split function to get each line separately:
Suppose you have a function called ClipBoard_GetData that returns the text from ClipBoard, you could use something like this:
Dim lines() As String
lines = Split(ClipBoard_GetData, vbNewLine)
For Each Line In lines
' Parse each line to get whatever parts you want
Next
This should work fine.. and if you don't -already have a function that gets what's in the clipboard, you could refer to this link
Hope that helps :)
Most likely the Ascii code you're after is 10 (ie newline). So you could find the position of the newline like so:
i = Instr(str, Chr(10))
However, are you aware that you don't need to parse that clipboard text at all. You can write arrays directly into worksheet cells. So all you'd need to do is use the Split function. The procedure below will complete everything you need:
Public Sub PasteText(str As String)
Dim arr() As String
Dim cols As Integer
arr = Split(str, Chr(10))
cols = UBound(arr) + 1
Sheet1.Range("A1").Resize(, cols).Value = arr
End Sub
I am successfully replacing a text in a file.
Dim fileReader As String = My.Computer.FileSystem.ReadAllText("C:\test.txt").Replace("foo", "bar")
My.Computer.FileSystem.WriteAllText("C:\test.txt", fileReader, False)
But how can I replace if I don't know the middle of the text ? For example
example_my("browser.taskbar.lastgroupid", "E7CF176E110C211B");
How to replace the E7CF176E110C211B ?
One way is to use RegEx. You can specify the first and last parts and then use \d+ or better [0-9A-F]+ to match any hex number. So given that the part that you don't know is a hexadecimal number, you can use the following code:
Dim fileReader As String = My.Computer.FileSystem.ReadAllText("C:\test.txt")
fileReader = System.Text.RegularExpressions.RegEx.Replace(fileReader, "[0-9A-F]+", "bar")
My.Computer.FileSystem.WriteAllText("C:\test.txt", fileReader, False)
This will replace all hexadecimal numbers in the file with the word "bar".
Note that for a text file this kind of global Replace can have undesirable results. For example the above regex will replace letters A to F even within normal text. So you'll probably want to put some kind of limitations such as min. number of digits to make sure it replaces only valid hex numbers. For example you may want to use [0-9A-F]{4,} which will replace only 4 or more consecutive hex digits. But even that is not 100% safe; e.g. it will replace DEAD, FACE, FADE, FACED etc. with the word "bar". To figure out exactly what is 100% safe for your file, you'll need to examine its contents carefully.
Edit
Reading you comments, you can use the following code instead:
Dim fileReader As String = My.Computer.FileSystem.ReadAllText("C:\test.txt")
fileReader = System.Text.RegularExpressions.RegEx.Replace(fileReader , "lastgroupid"", ""(.+)""\)", "lastgroupid"", ""ANYTHING_YOU_WANT""\)")
My.Computer.FileSystem.WriteAllText("C:\test.txt", fileReader, False)
This will replace all occurrances of hex numbers between lastgroupid", " AND ") with the string ANYTHING_YOU_WANT.
To start here is an example of a line I am trying to manipulate:
trait slot QName(PrivateNamespace("*", "com.company.assembleegameclient.ui:StatusBar"), "_-0IA") type QName(PackageNamespace(""), "Boolean") value False() end
I wrote a code that will go through and read through each line and stop at the appropriate line. What I am trying to achieve now is to read through the characters and save just the
_-0IA
to a new string. I tried using Trim(), Replace(), and indexof so far but I am having a ton of difficulties because of the quotation marks. Has anyone deal with this issue before?
Assuming your source string will always follow a strict format with only some data changes, something like this might work:
'Split the string by "," and extract the 3rd element. Trim the space and _
quotation mark from the front and extract the first 5 characters.
Dim targetstr As String = sourcestr.Split(","c)(2).TrimStart(" """.ToCharArray).Substring(0, 5)
If the length of the target string is variable it can be done like this:
Dim temp As String = teststr.Split(","c)(2).TrimStart(" """.ToCharArray)
'Use the index of the next quotation mark instead of a fixed length
Dim targetstr As String = temp.Substring(0, temp.IndexOf(""""c))
I want to insert a word inside an existing word? Both are Strings.
For example:
Given String word:
HELLO SAMPLE SENTENCE
i want to insert the word I AM A so my output would be:
HELLO I AM A SAMPLE SENTENCE
i am inserting here basing on the word SAMPLE. So the insertion starts before the word SAMPLE. is this possible?
Based on the description of your logic (which isn't much to go on), I would use:
Dim input As String = "HELLO SAMPLE SENTENCE"
Dim iSample As Integer = input.IndexOf("SAMPLE")
Dim output As String = input.Insert(iSample, "I AM A ")
This uses the BCL function String.Insert, which simply inserts a string into another string at a particular position.
Create a function like this:
Function InsertBefore(sentence As String, find As String, textToInsert As String
Return sentence.Replace(find, textToInsert+Find)
End Function
And call it like this:
sentence = InsertBefore("HELLO SAMPLE SENTENCE", " SAMPLE ", "I AM A")
If I remember correctly, you can use the String.split() function on your string.
See DotNetPerls' page on Split here.
You can split the string into an array, then insert the line you want into the array, then join them back together using String.Join() (thanks Monty, I don't use Visual Basic that frequently anymore, I forgot that :)).
Hope this help :)
In one of the ms-access table I work with we have a text field with a set size.
At the end of this field there is some extra code that varies depending on the situation.
I'm looking for a way to remove one of these code but even when the last part is truncated by the field maximum size.
Let's call the field "field" and the code I'm looking to remove "abc-longcode".
If I use the replace SQL function with the string abc-longcode the query will only work when the code is complete.
If I also want my update query (that does nothing but remove this specific code at the end of my field) to work on incomplete codes how would that translate into ms-SQL?
It would have to remove (or replace with "" to be precise) all of the following (example of course, not the real codes):
abc-longcode
abc-longcod
abc-longco
abc-longc
abc-long
abc-lon
abc-lo
abc-l
Obviously I could do that with several queries. Each one replacing one of the expected truncated codes... but it doesn't sound optimal.
Also, when the field is big enough to get all of the code, there can sometime be extra details at the end that I'll also want to keep so I cannot either just look for "abc-l" and delete everything that follows :\
This query (or queries if I can't find a better way) will be held directly into the .mdb database.
So while I can think of several ways to do this outside of a ms-sql query, it doesn't help me.
Any help?
Thanks.
You can write a custom VBA replace method that will replace any of the given cases {"abc-longcode", ... "abc-l"}. This is essentially the same tack as your "several queries" idea, except it would only be one query. My VBA is rusty, but something like:
public function ReplaceCodes(str as string) as string
dim returnString as string
returnString = str
returnString = replace(returnString,"abc-longcode","")
// ... etc...
ReplaceCodes = returnString
end function
I may have gotten the parameter order wrong on replace :)
I would use my own custom function to do this using the split function to get the first part of the string. You can then use that value in the update query.
Public Function FirstPart(thetext As String) As String
Dim ret As String
Dim arrSplitText As Variant
arrSplitText = Split(thetext, "-")
ret = arrSplitText(0)
FirstPart = ret
End Function
Can you use:
Left(FieldX,InStr(FieldX,"abc-")-1)
EDIT re Comment
If there is a space or other standard delimiter:
IIf(InStr(InStr(FieldX, "abc-"), FieldX, " ") = 0, Left(FieldX, InStr(FieldX, "abc-") - 1), Replace(FieldX, Mid(FieldX, InStr(FieldX, "abc-"), InStr(InStr(FieldX, "abc-"), FieldX, " ") - InStr(FieldX, "abc-")), ""))