0

i need to make a regex that matches either a or c on the first slot, "the char(0)" but i only know how to use from A-Z

   string.matches(("^[A-C]{3}$")) //this includes B, i dont want this to happen

Can i add a string? or a char variable? insteas of the a and c? like

  "[+ char +]"

?

1
  • ^[ac] is a regex that matches a or c as the first character of the string. But you don't need a regex to do this. Commented Oct 21, 2014 at 15:54

3 Answers 3

2

When you use - in a character class expression, you allow the first character, the last character, and everything in between. Hence, A-C means 'A', 'B', or 'C'. If you want either 'A' or 'C', use [AC] instead:

string.matches(("^[AC]{3}$"))

Can I add a String or a char variable?

Yes, if you obey the general rules of character class expressions:

  • If you have a - or a ^ in your String, put them at the back
  • If you have a ] or \ characters in your String, add an escape character in front of them.

Assuming that there are no special characters in your string, you can do

String str = "ac";
string.matches(("^[" + str + "]{3}$"))
Sign up to request clarification or add additional context in comments.

Comments

1

try "^[AC]{3}$"

The brackets match only a single character, so in this case they will match only A or C

Comments

1

First you should have done some research in the internet: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html . This will give you very good tutorial on regex.

According to that link you should try:

string.matches(("^[AC]{3}$")) 

Hope that helps

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.