0

I am teaching myself regex using a combination of the two websites Eloquent JavaScript and regular expressions.info. I am trying to use back references via a self made example in which I want to roughly be able to test for syntactic correctness of a Java while loop (assuming we limit it to while( value operator value) for the sake of simplicity).

However take a look at my code below and you will see that the reference \1 does not appear to work. I've tried my solution in JS. but also using software tool The Regex Coach.

Can anyone see the problem here?

var rx = /^while\s*\((\s*[a-zA-Z][a-zA-Z0-9_]*\s*)(\<\=|\<|\>\=|\>|\!\=|\=\=)\s*\1\)/

document.writeln(rx.test("while(x <= y)"));

1 Answer 1

1

Your regex would match

while(x <= x )

because \1 matches the exact text that was matched by the first capturing group - which in this case is "x ". And since "y" isn't the same as "x ", your regex fails on the example you've chosen.

For your example, the following would work:

var rx = /^while\s*\(\s*([a-zA-Z]\w*)\s*(<=?|>=?|!=|==)\s*([a-zA-Z]\w*)\s*\)$/

Note that \w is a shorthand for [a-zA-Z0-9_] in JavaScript, and that you don't need to escape all those symbols.

Sign up to request clarification or add additional context in comments.

4 Comments

I can't even get a match on your example. So what you are saying is there is no way to do what I want?
@Andrew S: note the whitespace around the x characters (I was about to give a similar answer as Tim)
Oh yes I see. So is there a way to do what I need?
@AndrewS: You can't use a backreference - you have to copy the part of the regex that you need to reuse.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.