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
492 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 75

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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 75

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 75

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
 
LVL 75

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 75

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 75

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 75

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

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
VB.Net - String Manipulation Scenario 2 29
Vb.net threads keep increasing 2 49
VB.net -  GroupBox / Panel DataBinding and behavior 3 23
Visual Studio npm 1 29
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
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…

761 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