Results 1 to 3 of 3
- 09-21-2008, 12:08 PM #1
Member
- Join Date
- Sep 2008
- Posts
- 6
- Rep Power
- 0
Regular expressions from command prompt
I'm writing a program which takes four command-line arguments:
(1) Input file
(2) Output file
(3) Pattern to match
(4) Text to replace with
The goal of the program is to take the input file and replace all patterns (a regular expression specified by argument 3) with a text (argument 4) and then write the results to another file (argument 2).
I've written the program and it works just fine, but I've had some problems with argument specifying the text to replace with.
How would I specify that I want to delete the pattern if found?
My solution was that for deleting the pattern you would just run the program without the fourth argument.
e.g. If I want to delete all "gg" or "cc" strings from the file:
java TextReplacer input.txt output.txt [gc]{2} (I just ommit the fourth argument)
Part of the code that deals with command line arguments:
Is there a more elegant way of doing this, something like actually entering the replacement string that means 'no character' or something of that kind?Java Code:public class TextReplacer { public static void main(String[] args) { String inputFilename = args[0]; File inFile = new File (inputFilename); String outputFilename = args[1]; File outFile = new File (outputFilename); String searchPattern = args[2]; String replacementString; //if no replacement string is provided, program just deletes the search pattern if (args.length < 4) replacementString = ""; else replacementString = args[3];
I'm using the replaceAll method from the Matcher class to do the actual string replacement
- 09-21-2008, 02:15 PM #2
A comment; Test that there are at least 3 args before trying to use them.
- 09-21-2008, 02:40 PM #3
Member
- Join Date
- Sep 2008
- Posts
- 6
- Rep Power
- 0
Similar Threads
-
Using Quantifiers in regular expressions
By Java Tip in forum Java TipReplies: 0Last Post: 01-10-2008, 10:43 AM -
Handling regular expressions using Regex
By Java Tutorial in forum Java TutorialReplies: 0Last Post: 01-07-2008, 12:46 PM -
Capturing Groups using regular expressions
By Java Tip in forum Java TipReplies: 0Last Post: 12-25-2007, 11:19 AM -
Regular expressions quantifiers
By Java Tip in forum Java TipReplies: 0Last Post: 12-25-2007, 11:18 AM -
regular expressions and string matching
By DennyLoi in forum New To JavaReplies: 1Last Post: 11-16-2007, 10:15 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks