Hello,
With the code below, I am trying to replace all regex matches for visa cards within a given text file.
My first test was with a text "new3.txt" exclusively containing the visa test card 4111111111111111. My objective was to replace the card with "xxxx-xxxx-xxxx-xxxx". This was successful.
However, when modifying the text file to include other characters and text before and after (ex: " qwerty 4111111111111111 adsf zxcv"), it gives mixed results. Although it successfully validates the match, it replaces the whole text in the file, rather than replacing solely the match.
When trying this search and replace with words (rather than a regex match), it does not have this behavior. What am I missing?
import java.io.*; import java.util.regex.*; public class BTest { //VISA Test private final static String PATTERN = "(?s).*\\b4[0-9]{12}(?:[0-9]{3})?\\b.*"; public static void main(String args[]) { try { File file = new File("c:/eclipse/new3.txt"); BufferedReader reader = new BufferedReader(new FileReader(file)); String line = "", oldtext = ""; while((line = reader.readLine()) != null) { oldtext += line + "\r\n"; } reader.close(); String newtext = oldtext.replaceAll(PATTERN, "xxxx-xxxx-xxxx-xxxx"); FileWriter writer = new FileWriter("c:/eclipse/new4.txt"); writer.write(newtext);writer.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }