I want to create a small window where a user will :
- Enter some text in JTextField1.
- Then he will enter a regular expression in JTextField2 to check if the text in JTextField1 has some text matching this Regex.
- And another field JTextField3 that he can enter a formating for the matching text
- The user will then get the final text matching this and formatted in JTextField4.
This seems to be complicated, but i hope this screenshot will clarify my needs :
Implementing the first 2 fields was easy, but the third field, that is what i want to ask about. I have read about Back references that can help me do that, but it is not so clear to me. What i understand is that if i wrote \2, \1 as it appears in the screenshot, then it will grab the second bracket in the Regex then adds a comm开发者_StackOverflow社区a + a space then grabs the first bracket in the Regex, giving the right final result.
1. Is this right, or am i missing something ?
2. Is this the best solution to implement what i need to do ?
3. After getting the matcher in Java code = Returns "K1234 T1234567" what is the code to format it using the specified format ?
What you have looks right. You'll need something like this to get the result formatted:
// your inputs for the sake of a working example snippet
String text = "K1234 T1234567";
String query = "([A-Z]{1}[0-9]{4})((\\ ){1})([A-Z]{1}[0-9]{7})";
String format = "\\4, \\1";
// usual regex pattern matching
Pattern pattern = Pattern.compile(query);
Matcher matcher = pattern.matcher(text);
matcher.find();
// you need to tweak the format to use $ instead of \ for replacement
String replacement = format.replaceAll("\\\\", "\\$");
String result = matcher.replaceAll(replacement);
// this outputs "T1234567, K1234"
System.out.println(result);
精彩评论