1

I am checking for precedence in a string in my function. Is there a way to change my code to incorporate regex -- I am quite unfamiliar with regex, and though I have read some tutorials online, still not getting 'it' too well. So any guidance would really be appreciated.

For example in a string XLYZ, if the char after X is not L or C, the 'violation' statement gets printed. Here's the code below:

if (subtnString[cnt]=='X' && cnt+1<subtnString.length){
                if(subtnString[cnt+1]!= 'L' || subtnString[cnt+1]!= 'C'){
                    System.out.println("Violation: X can be subtracted from L and C only");
                    return  false;
                }
            }

Is there a way I can use regex to replace this code?

2 Answers 2

6

You can use something like this:

Pattern regex = Pattern.compile("^X[LC]");
Matcher regexMatcher = regex.matcher(subjectString);
if(regexMatcher.find() )  { // it matched!
}
else { // nasty message
     }

In the demo, see the strings that match.

Explanation

  • The ^ anchor asserts that we are at the beginning of the string
  • X matches the literal X
  • [LC] is a character class that matches either one L or one C

Reference

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

3 Comments

Given these explanations, XLYZ doesn't match the regex.
Great answer! The only thing I would add is that you should check tou the Documentation on Strings in Java. You can browse all the methods it provides for working with strings.
@zx81 yes, we do match the whole string.
1

to match texts that violate your rule use this regex:

X[^LC]

see Demo

and to match regex that do not violate your rule use this:

X[LC]

see Demo

Comments

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.