Sign in to follow this  

Java Pattern Matcher reads white space wrong

Recommended Posts

As my project is beginning to take shape, most of the problems I've encountered, I've been able to solve, but this latest one cunningly beats me, not because of any complexities but  because I don't know whats going on under the hood of the parser.

I am using a pattern matcher() Pattern.compile("\\d+");  - (in JAVA) - to extract and read floats,   but there were problems as white spaces are being interpreted as 0.0


but should, correctly, be something like this

808.0  472.0  36.0  202.0  18.0  24.0
782.0  96.0  36.0  202.0  18.0  24.0
909.0  1028.0  36.0  202.0  18.0  24.0
931.0  1149.0  36.0  202.0  18.0  24.0

It was wrong because it was making white space to be 0.0

As said It was wrong because it was making white space to be 0.0

My quick fix was to use an if statement that exclude 0.0.  

Well I got away with it until the inevitable began to happen,- some of the real data started turning out to be 0.0, so my if statement was excluding the  real data from being read.  Any help on how to get this fixed?  I need white space to be read as white space not as 0.0 

public void readDataFromSelectedTextFile( File fPathplusName  ){
		List<Float> numbers = new LinkedList<Float>();
	   try {
				bufferedReader = new BufferedReader(new FileReader(fPathplusName));
				while ((stringObjectData = bufferedReader.readLine()) != null){
					Pattern p = Pattern.compile("\\d+");
					Matcher m = p.matcher(stringObjectData);
					while (m.find()) {
				ListIterator<Float>  floatIterator = numbers.listIterator();			
				int i=0, t=7, n=0;
				float s, size=0;                         
			    while( floatIterator.hasNext() ){
			    	if( (s = > 0 ){
                                      ...  plenty of good coding here ...
	      catch (FileNotFoundException e) {		
	      catch (IOException e) {


Edited by grumpyOldDude

Share this post

Link to post
Share on other sites

I don't think whitespace is your problem.


I think your problem is that \d "digit" doesn't match '.' characters (I use C# not Java, but regular expressions should be basically the same, shouldn't they?), so when you see x.y  your regular expression finds x, skips . and then returns a second match for y.


Try using "[0-9\\.]+" instead, or if you want to be more exact:  "[\\-\\+]?[0-9]*(\\.[0-9]+)?"  (but this does not include the 10E+5 syntax.  left as an exercise to the reader)

Edited by Nypyren

Share this post

Link to post
Share on other sites

Oh dear, I completely forgot ...  Many thanks Nypyren,  your answer triggered further inspiration on how it works.  And so I replaced   Pattern p = Pattern.compile("\\d+");  with    Pattern p = Pattern.compile("\\d+\\.\\d+");   and  the algorithm read my data correctly. Thanks

Edited by grumpyOldDude

Share this post

Link to post
Share on other sites
1 hour ago, grumpyOldDude said:

Oh dear, I completely forgot ...  Many thanks Nypyren,  your answer triggered further inspiration on how it works.  And so I replaced   Pattern p = Pattern.compile("\\d+");  with    Pattern p = Pattern.compile("\\d+\\.\\d+");   and  the algorithm read my data correctly. Thanks

This will probably break if you ever have negative values, or forget to put in the fractional part.  That may or may not be a problem, depending on what your data is here.

Nypren's more exact regex would get around that.

If I knew I had a file full of white-space delimited floats, I would probably not bother with trying to use a regex at all, and instead, what I would probably do would be something like (also a C# guy...):

var numbers = new List<float>();
var lines = File.ReadAllLines("whatever.txt");
float f;
foreach (var line in lines){
	var values = line.Split(new[]{' ', '\t', '\r', '\n'}, StringSplitOptions.RemoveEmptyEntries));
	foreach( var value in values ) {
		if (float.TryParse(value, out f)){

The Jamie Zawinski quote gets thrown out probably more than it should, but...


"Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems."


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Forum Statistics

    • Total Topics
    • Total Posts
  • Similar Content

    • By shillhunter
      I'm looking to add some new experience so I can get better at development, so I'm looking to join a team. I'm great with retro pixel art, even better with reference images (below is an example of my pixel art work), and I just started learning about mobile development. More specifically, Android Studio, though I am trying to expand my horizons. I have great programming experience, and am versatile. I took one year of C++ at my school, and studied Java independently. I'd like to find a team to join that's working on a 2D pixel art game for Android phones.

    • By sang_261198
      Hi everyone.
      My name is Sang and I am a student in primary school. I studied Java and  i am really like it.
      and now I want to learn make game a game use Java in Java Swing. Would you like give me some websites teach make game java for begginers, please?
      Thank you very much!
    • By yoel1234
      i created 10 more programming tutorial videos about how to use my game framework.
      i hope this will help people develop games and learn game programming in general.
      if you have any feedback i would love to hear about it.
    • By Giannis Marinakis
      Hello everyone!
      I have a GitHub repository on which I'm developing a Open Network Library for Java Developers and I'd like to share it so more people come in and contribute. Till now the repo is being developed only by me so the library is not 100% bug free. I'd really like this repo to be famous and got people working on it!
      [You will find more information in the repo]
      Here's the link for the repo:
    • By PaCkEtPiRaTe
      I'm currently remaking a game I made a few years back using Slick2D (as opposed to Swing/AWT, which was a terrible idea). I've fleshed out a lot of the background architecture, but I'm starting to run into issues with my architecture and I'm not sure how to proceed.
      The game I'm making is an overhead shooter. It's wave-based, with hordes of zombies coming at you. There are 10 weapons to choose from.
      Specifically, my latest issue is with a particular "weapon" I'm designing; the Laser Barrier. In the previous game, I had a "Laser Wire" weapon, which when two terminals were placed on the ground, created a wire made of laser on the ground that would damage enemies that passed through. Problem was that it didn't do enough damage in the short time that the enemies would be colliding with it for it to be of any use, so it was a waste of money.
      In the remake, I'm instead creating the "Laser Barrier", which visually looks the same, but instead of damaging enemies that touch it, it will act as an obstacle that enemies can't walk through. The enemies damage the shield while they are in contact with it until the laser barrier collapses. Projectiles however, can still pass through the barrier, allowing the player, and certain enemies, to shoot through them.
      The issue I'm running into, though, is the method of communicating between the Laser Wire itself and the enemy touching it. I'm currently able to detect a collision between the enemy and wire projected between the two laser terminals, but I'm not sure how I can implement the actual movement blocking part.
      It would take too much text to explain how it works, so here are the relevant files in my project:
      Player class - the checkProjectiles() method on line 344 is where the game loop checks for collisions between the player's weapon projectiles and the an enemy passed as an argument. On line 350, you can see that when there is a collision between the enemy and the LaserNode object (collision method is linked below), the laser node takes damage so that it will eventually be destroyed. I figured this is where the "movement blocking" should be, as I have access to the terminal and the enemy, and this is where a collision is confirmed. LaserNode class - this is the class representing the laser terminals on the ground that project the laser beam between them. The checkCollision() method on line 57 is used to determine if the enemy is touching either of the terminals, or if it is touching the beam itself. Enemy class - this is the base class for all game enemies. You can see what methods are available to all enemies, so perhaps this can provide some insight into what could be done to communicate with the LaserNode. I realize it's a lot to ask considering the scope of my project, but could someone give me an idea of how to communicate between the LaserNode and Enemy so that the enemy knows not to move when touching the LaserNode? The only methods I can think of seem cumbersome and it seems like I'd be adding a lot to the Enemy class just to get this one feature working.
      I'd love to script these weapons with LUA, but I never learned how to integrate a scripting language into my game architecture. I also have limited experience writing game engines, so I'm sure there's a lot of refinement that could be done to make my game architecture less restricting.
      I don't expect anyone to actually comb through my project and make suggestions, but I would super appreciate it.
  • Popular Now