Home > Net >  Reformat String to only have numbers
Reformat String to only have numbers

Time:05-07

I have a string that I would like to reformat but I'm unsure how to do so

  • for context, I am coding in Java
document(_id:62761f225fb9f87294f485d3 id:376244886976069635 room:"0 1 0 2 3 = 0 1 2 4 3 = 1 0 0 0 2 = 4 3 2 4 0 = 1 0 2 0 3 ="
cash:"100")

I would like to reformat this string to only have the numbers after room: like so.

0 1 0 2 3 0 1 2 4 3 1 0 0 0 2 4 3 2 4 0 1 0 2 0 3

CodePudding user response:

If you have a constant number of digits between =, then would this be a solution:

((\d\s){5})

https://regex101.com/r/G6SQar/1

This would set all the numbers as separate groups. You can then use the Matcher class in Java to extract all the groups and concatenate them to get your required string. Details on how this can be done can be found in this answer. Additionally, if you are using JDK 8 , you might want to use streams, something like this.

CodePudding user response:

We can use a regex with some callback logic:

String input = "document(_id:62761f225fb9f87294f485d3 id:376244886976069635 room:\"0 1 0 2 3 = 0 1 2 4 3 = 1 0 0 0 2 = 4 3 2 4 0 = 1 0 2 0 3 =\"\ncash:\"100\")";
Pattern p = Pattern.compile("\\broom:\".*?\"");
Matcher m = p.matcher(input);
StringBuffer buffer = new StringBuffer();
  
if (m.find()) {
     String replace = m.group().replaceAll(" = ", " ");
     m.appendReplacement(buffer, replace);
}
m.appendTail(buffer);
System.out.println(buffer.toString());

This prints:

document(_id:62761f225fb9f87294f485d3 id:376244886976069635 room:"0 1 0 2 3 0 1 2 4 3 1 0 0 0 2 4 3 2 4 0 1 0 2 0 3 =" cash:"100")

The idea here is to find the room term in the input string, then pause to further modify it by removing all equals signs from the numbers string.

CodePudding user response:

You can use this pattern with a positive look-back to check that there is room:" before. We accept any combination of \d numbers : and = 1 or more times .
We will then need to replace = with an empty string "".

(?<=room:\")[\d =] 

See https://regex101.com/r/wdPF79/1

  • Related