Reputation: 964
I am trying to pick the integer value 30
in this string which hast the form \s\d\d\s. I have tried the code below but I am getting the Minute value 30 at the end of the line too but I want just to get the value 30
which has this form \s\d\d\s
. How can I fix that?
I appreciate any help.
Line before doing m.group(); in this line are two 30 number
wall street 4 06:28 07:29 07:59 08:29 08:59 30 19:59 20:29 21:04 22:04 23:04 00:04 00:30
Line after:
wall street 4 06:28 07:29 07:59 08:29 08:59 19:59 20:29 21:04 22:04 23:04 00:04 00:
Result should Looks like
wall street 4 06:28 07:29 07:59 08:29 08:59 19:59 20:29 21:04 22:04 23:04 00:04 00:30
my Code:
Pattern pattern = Pattern.compile("(?<=\\d\\s)\\d{2}(?=\\s\\d)");
Matcher m = pattern.matcher(line);
while (m.find()) {
value = Integer.parseInt(m.group().trim());
line = line.replace(m.group(), " ").replaceAll(" +", " ");
}
Upvotes: 2
Views: 87
Reputation: 167822
Instead of using a independently calling line.replace(m.group(), " ").replaceAll(" +", " ");
you can use the matcher's replace functions.
Like this:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main (String[] args) throws java.lang.Exception
{
String line = "wall street 4 06:28 07:29 07:59 08:29 08:59 30 19:59 20:29 21:04 22:04 23:04 00:04 00:30";
System.out.println( "Input: " + line );
Pattern pattern = Pattern.compile("(?<=\\d{2}:\\d{2})\\s+\\d{2}(?=\\s)");
Matcher m = pattern.matcher(line);
while (m.find()) {
int value = Integer.parseInt(m.group().trim());
line = m.replaceFirst("");
System.out.println( "Output: " + line );
}
}
}
Upvotes: 0
Reputation: 13640
Why is it happening?
Your pattern is OK and matching 30
as required.. but in the while
loop.. you are replacing m.group()
(which is now 30
) with " "
.. hence all the instances where you have 30
will be replaced..
How to fix?
You can replace the pattern directly.. i.e:
line = line.replaceAll("(?<=\\d\\s)\\d{2}(?=\\s\\d)", "").replaceAll(" +", " ");
Code:
Pattern pattern = Pattern.compile("(?<=\\d\\s)\\d{2}(?=\\s\\d)");
Matcher m = pattern.matcher(line);
while (m.find()) {
value = Integer.parseInt(m.group().trim());
}
line = line.replaceAll("(?<=\\d\\s)\\d{2}(?=\\s\\d)", "").replaceAll(" +", " ");
System.out.println(line);
See Ideone Demo
Upvotes: 1
Reputation: 784928
You can just do:
line = line.replaceAll("(?<=\\d\\s)\\d{2}\\s*(?=\\d)", "");
to get your output.
Upvotes: 3