Solved

How to insert, if there is search and replace can't find required string via regular expressions in vb.net

Posted on 2011-02-22
16
484 Views
Last Modified: 2012-08-13
I am using this match pattern
"^(user_pref\(\s*""browser\.startup\.homepage"",\s*"")[^""]*("")"

Open in new window


to find this string
user_pref("browser.startup.homepage", http://www.google.com");

Open in new window

and replace with my own.

Sometimes what happens, this string is not present in file and therefore i can't be searched and replaced, in that condition i want to insert one string of my own
user_pref("browser.startup.homepage", http://www.google.com");

Open in new window

but also have to make sure if string is already present then it should be replaced instead of inserting. because if unproperly done it will leave two strings.

I actually don't know proper syntax to do stream reader and write the thing in vb.net so unsure whether this thing comes under regular expressions or streaming.
0
Comment
Question by:herit02
  • 8
  • 7
16 Comments
 

Expert Comment

by:bergerge
ID: 34951597
Hello Herit02,

I suggest to flatly remove an existing line with the prefix    user_pref("browser.startup.homepage"
with the search-pattern
 "^(user_pref\(\"browser\.startup\.homepage"

After the removal you now can add the desired line without the fear of duplicate lines:
user_pref("browser.startup.homepage", http://www.anysearchengine.com");

Kind regards
George
0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 34952048
Try this:
Dim yourString As String = "your replacement strign"
Dim pattern As String = "^(user_pref\(\s*""browser\.startup\.homepage"",\s*"")[^""]*("")"
Dim yourFilename As String = "yourfilename.txt"

Dim found As Boolean = False
Dim temp As String = System.IO.Path.GetTempFileName()

Using reader As New System.IO.StreamReader(yourFilename)
    Using writer As New System.IO.StreamWriter(temp)
		While Not reader.AtEndOfStream
			Dim m As System.Text.RegularExpressions.Match
			Dim line As String = reader.ReadLine()

			m = System.Text.RegularExpressions.Regex.Match(line, pattern)

			If m.Success Then
			    found = True
			    
			    line = System.Text.RegularExpressions.Regex.Replace(line, pattern, yourString)
			End If
			
			writer.WriteLine(line)
		End While
		
		If Not found Then
		    writer.WriteLine(yourString)
		End If
	End Using
End Using

System.IO.File.Move(temp, yourFilename)

Open in new window

0
 
LVL 3

Author Comment

by:herit02
ID: 34953059
Dear kaufmed,
Actually i am pretty bad at stream writing and reading, i tried my best but getting some errors, so could you merge your solution into following code. if possible for you, keep the variables intact in the way i assigned them.
I have regex.replace code so you just add a few lines to find match and insert if nothing get found.

   Private Sub performtask()
        Dim fso, inputFile, outputFile
        Dim str As String
        Dim myFile As String = "c:\configuration.txt"
        fso = CreateObject("scripting.filesystemobject")
        inputFile = fso.OpenTextFile(myFile, 1)
        str = inputFile.ReadAll
        Dim found As Boolean = False
        Dim joiner As String = "$1" & TextBox1.Text & "$2" 'textbox1 contains http://www.somewebsite.com
        Dim replacementstring As String = joiner
        Dim matchpattern As String = "^(user_pref\(\s*""browser\.startup\.homepage"",\s*"")[^""]*("")"
        'here comes the actual replacement. 
        str = Regex.Replace(str, matchpattern, replacementstring, RegexOptions.Multiline)
        outputFile = fso.CreateTextFile(myFile, True)
        outputFile.Write(str)
        MsgBox("Done")
   End Sub

Open in new window

0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 34953156
Is this VB.NET, or VBA? If .NET, why in the world are you using

    CreateObject("scripting.filesystemobject")

There are already classes built into .NET to perform reading of files. You should not need to rely on CreateObject for such things.
0
 
LVL 3

Author Comment

by:herit02
ID: 34953215
i don't much about these, but this was how i received the code.
neway could you try adding your solution into this existing one?
if require you may remove create object and use inbuilt class.
thanks so much for helping me out!
0
 
LVL 3

Author Comment

by:herit02
ID: 34953608
i tried your way
but its giving me following error
"AtEndOfStream is not a member of system.io.streamreader"
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 34954576
>>  "AtEndOfStream is not a member of system.io.streamreader"

That's my fault--the correct property is "EndOfStream". That's what I get for trying to code from memory  = )
0
 
LVL 3

Author Comment

by:herit02
ID: 34954794
when i go by that method, it gives exception that file is already in use.
i troubleshooted 5-10 times whether any process was using it but no process was.
kaufmed, it would be very grateful of you if you could implement yourself your solution in to mine.

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 34955041
Which file (or which line of code) is generating the exception?
0
 
LVL 3

Author Comment

by:herit02
ID: 34955067
"Using writer As New System.IO.StreamWriter(yourFilename)"
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 34955427
That's incorrect. Look at lines 8 & 9 in post http:#34952048 . The reader should point to "yourfilename" and the writer should point to "temp".
0
 
LVL 3

Author Comment

by:herit02
ID: 34955563
i actually tried with temp too.
ok re-tried for confirmation with using temp but it gives error that the file already exists and then it does not allow to move.
0
 
LVL 3

Author Comment

by:herit02
ID: 34955616
It goes to last line when it actually replaces temp file with original one,
and this error comes
Cannot create a file when that file already exists.
0
 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 500 total points
ID: 34955999
Let's use Copy() instead of Move(). Copy() optionally takes a third parameter specifying whether or not to overwrite existing files:
System.IO.File.Copy(temp, yourFilename, true)

Open in new window

0
 
LVL 3

Author Closing Comment

by:herit02
ID: 34956597
Hey thanks so much for helping me out.
It really did solved problem finally...

btw why it didn't allowed me when we used move and replace instead of copy and replace


Cheers!,
Herit
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 34957600
>>  btw why it didn't allowed me when we used move and replace instead of copy and replace

I believe it's by design. I thought Move() had an overload to specify overwrite, but I was mistaken. This is why I suggested the use of Copy() instead.

Glad to help  : )
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now