Domanda

I am reading some patterns from a file and using it in String matches method. but while reading the patterns from the file, the escape characters are not working

Ex I have few data ex "abc.1", "abcd.1", "abce.1", "def.2"

I want do do some activity if the string matches "abc.1" i.e abc. followed by any characters or numbers I have a file that stores the pattern to be matched ex the pattern abc\..*

but when I read the pattern from the file and using it in String matches method it does not work.

any suggestions

a sample java program to demonstrate the issue is :

package com.test.resync;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class TestPattern {

    public static void main(String args[]) {
        // raw data against which the pattern is to be matched
        String[] data = { "abc.1", "abcd.1", "abce.1", "def.2" };

        String regex_data = ""; // variable to hold the regexpattern after
        // reading from the file

        // regex.txt the file containing the regex pattern
        File file = new File(
                    "/home/ekhaavi/Documents/WORKSPACE/TESTproj/src/com/test/regex.txt");

        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String str = "";
            while ((str = br.readLine()) != null) {
                if (str.startsWith("matchedpattern")) {
                    regex_data = str.split("=")[1].toString(); // setting the
                                                               // regex pattern

                    }
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        /*if the regex is set by the below String literal it works fine*/

        //regex_data = "abc\\..*"; 

        for (String st : data) {
            if (st.matches(regex_data)) {
                System.out.println(" data matched "); // this is not printed when the pattern is read from the file instead of setting it through literals
            }
        }
    }

}

The regex.txt file has the below entry

matchedpattern=abc\..*

È stato utile?

Soluzione

Use Pattern.quote(String) method:

if (st.matches(Pattern.quote(regex_data))) {
     System.out.println(" data matched "); // this is not printed when the pattern is read from the file instead of setting it through literals
}

There are some other issues that you should consider resolving:

  • You're overwriting the value of regex_data in the while loop. Did you intend to store all the the regex pattern in a list?

  • String#split()[0] will return a String only. You don't need to invoke toString() on that.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top