'How to separate files, number wise using regular expressions in java/shell?
I want to separate below numbers like as(00 to 04, 10 to 14, 20 to 24) 00000000000 00000000001 00000000002 00000000003 00000000010 00000000011 00000000012 00000000014 00000000020 00000000021 00000000022 00000000024 00000000030 00000000031 00000000032 00000000034 00000000100 00000000101 00000000110 00000000111 00000000120 00000000121
Solution 1:[1]
You can find each match with the following regex:
\d{11}\b
Here is a test
https://regex101.com/r/zruNcQ/1
If you need to create ranges only with continuous values (even though does not really respect your example, but it wasn't really clear). You could use a Scanner
to read each number with a while loop (no need for a regex) and check if the new number read interrupts the continuity of the current range.
public class Test {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new FileReader("test.txt"));
int from, to, temp;
List<Range> list = new ArrayList<>();
if (sc.hasNext()) {
//Reading the first range number and assigning it to the start and end of range
from = to = Integer.parseInt(sc.next());
//Reading the rest of the numbers
while (sc.hasNext()) {
//Reading the number
temp = Integer.parseInt(sc.next());
//Checking if the range is being continued
if (temp == to + 1) {
to = temp;
//Checking if the continuous range has been interrupted and saving the previous range
} else if (temp > to + 1) {
list.add(new Range(from, to));
from = to = temp;
}
}
//Saving the last range
list.add(new Range(from, to));
}
System.out.println(list);
}
}
class Range {
int from, to;
public Range(int from, int to) {
this.from = from;
this.to = to;
}
public String toString() {
return String.format("(%d - %d)", from, to);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |