Jump to content
  • Advertisement
Sign in to follow this  
Shakedown

[java] Why is my regular expression not working?

This topic is 3708 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

So I'm trying to determine whether a String (line) contains two labels (denoted LB#:). I've written a regular expression that I believe will determine this, but for some reason it's not working. In fact, none of my regular expressions work, even the simple ones. What's going on? Here's my code that does the iteration and checking:
BufferedReader file = new BufferedReader(new java.io.FileReader(filename + ".asms"));
	StringBuilder resulting_file = new StringBuilder();
		
	String line = "";
	String labelToReplace 	= "";
	String replaceWith		= "";
			
	String regex = ":\\D*\\d*:";
        // I've also tried String regex = ":[a-zA-Z0-9]*:";
			
	java.util.Hashtable<String, String> replacements = new java.util.Hashtable<String, String>();
			
	// Read over entire file
	while((line = file.readLine()) != null){
		//System.out.println(line);
		// If line has multiple labels
		if(line.matches(regex)){
			System.out.println("matched");
			// Separate the labels
			String fields[] = line.split(":");
			// Store the label to be replaced
			labelToReplace	= fields[1];
			// Store the label that will be used instead
			replaceWith		= fields[0];
					
			// Associate the labels to replace with their replacements
			replacements.put(labelToReplace, replaceWith);
					
			System.out.println(labelToReplace + " replaced by " + replaceWith);
					
			line = fields[0] + ":" + fields[2];
		}
				
		resulting_file.append(line + "\n");
	}

And here's the file that it checks:
.BEGIN
	IN	x
	PUSH	x
	PUSH	C0
	COMPARE
	JUMPGT	IF1
	JUMP	LS1
IF1:	PUSH	x
	PUSH	C10
	COMPARE
	JUMPLT	IF2
	JUMP	LS2
IF2:	OUT	x
LS2:LS1:	OUT	x   <------ REGEX SHOULD MATCH HERE
	HALT
x:	.DATA	0
C0:	.DATA	0
C10:	.DATA	10
.END

Share this post


Link to post
Share on other sites
Advertisement
The matches(String) method tries to match the whole String.

":[a-zA-Z0-9]*:"

does not match

"LS2:LS1: OUT x"

You probably want to do something like:

Pattern somePattern = Pattern.compile(":[a-zA-Z0-9]*:");

Matcher matcher = somePattern.matcher(line);
if(matcher.find()) { ... }

Both Pattern and Matcher classes are in the java.util.regex package.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!