Hi there,
Where's my code wrong? It didn't pass validation.
btw. I was looking for the appropriate REGEX for this taks with the following conditions:
* 1 dollar must be replaced by one dollar
* dollar 1 must be replaced by dollar one
* 1dollar must not be replaced
* dollar1 must not be replaced
I worked with the INTERNET page" https://regex101.com/" to see if my REGEX ("[^a-z^A-Z]\d+) worked and it did, In fact I copy the proposed code(*) by regex101 :to my IntelIiJ IDEA and it worked as expected however the same REGEX in the code of this task failed.????
(*)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "[^A-Z^a-z]\\d+";
final String string = "This costs 1 dollar, but this is 12.\n"
+ "The variable is called file1.\n"
+ "110 is a number.\n"
+ "1 dollar is the cost of 1 pigrim";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Surfing through the help I saw this new REGEX ("\\b\\d+\\b"), I checked it and it seems to be working but my code again didn't pass validation.
Thankspackage com.codegym.task.task19.task1924;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
Replacing numbers
*/
public class Solution {
public static Map<Integer, String> map = new HashMap<Integer, String>();
static{
map.put(0, "zero");
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
map.put(6, "six");
map.put(7, "seven");
map.put(8, "eight");
map.put(9, "nine");
map.put(10, "ten");
map.put(11, "eleven");
map.put(12, "twelve");
}
public static void main(String[] args){
String fileName = null;
// Getting the file name
try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))){
fileName = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
try (BufferedReader fileReader = new BufferedReader(new FileReader(fileName))) {
//final String REGEX ="[^A-Z^a-z]\\d+";
final String REGEX ="\\b\\d+\\b";
final Pattern pattern = Pattern.compile(REGEX);
while(fileReader.ready()){
String line = fileReader.readLine().trim();
Matcher matcher = pattern.matcher(line);
while(matcher.find()){
for(Map.Entry<Integer, String> pair : map.entrySet()){
if(Integer.parseInt(matcher.group(0).trim())==pair.getKey()) {
line = line.replaceFirst(matcher.group(0).trim(), pair.getValue());
break;
}
}
}
System.out.println(line);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}