Sign in to follow this  

[java] Why is my regular expression not working?

This topic is 3492 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
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

This topic is 3492 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.

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