0

I am trying to validate a RegEx string in Java but i cant get it to work properly. I am attempting to make sure the the following string "AB10XY" is always contained with the textField when performing a search.

I have the following line of code which ensures that AB and XY are in the textField but not the number:

boolean checkChar = ((textField.getText().contains("AB")) && (textField.getText().contains("XY")));

I would prefer to have something like :

boolean checkChar = ((textField.getText().contains("AB[\\d]{2}XY")));
3
  • ""AB10XY" is always contained with the textField when performing a search." Wouldn't it be simpler for you & the user to make that text field uneditable? Commented May 15, 2013 at 11:51
  • Were you intending to answer my question, or just ignore it? Note that there are probably better ways to go about this than using a RegEx, but until I have more details of the problem, it is hard to narrow them down. Commented May 15, 2013 at 12:26
  • Hi Sorry for the delay. i used one of the solutions listed below to fix the issue except i added brackets to the RegEx formula to say ".*[AB[\\d]{2}XY].*" it works perfectly so far. I am using this solution to check if "AB12XY" is in a path. eg : C:\Users\user\Documents\Handbacks\AB12XYmmmd (mmm=month, d=day) Commented May 15, 2013 at 14:11

4 Answers 4

1

You can try this way

boolean checkChar = ((textField.getText().matches(".*?AB[\\d]{2}XY.*")));
Sign up to request clarification or add additional context in comments.

1 Comment

@Anirudh true, but for some reason OP used it (maybe it will be expanded in real code)
1

I'm guessing the number isn't alway 10, so you should use something like this:

boolean checkChar = textField.getText().matches(".*AB[\\d]{2}XY.*");

Comments

0

Use package java.util.regex to handle RegEx

boolean checkChar = java.util.regex.Pattern.compile("AB[\\d]{2}XY")
        .matcher(textField.getText()).find();

Comments

0

Contains method doesn't support regex..You can use matches method

 textField.getText().matches(".*AB\\d{2}XY.*");

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.