1

I am trying to use regular expression to validate a string.

RegEx: "Coord=\\(.*\\);?" 

Issue: I am not able to find reg ex for following inputs and expected output

1. Input: Coord=(1,1) -- Expected output: True 2. Input: Coord=(1,1); -- Expected output: True 3. Input: Coord=(1,1): -- Expected output: False 4. Input: Coord=(1,1)abc -- Expected output: False 5. Input: Coord=(1,1);abc -- Expected output: True 

Any thoughts

1 Answer 1

2

You can alternate ";" with the end of the input to reach your goal:

String[] inputs = { "Coord=(1,1)",// -- Expected output: True "Coord=(1,1);",// -- Expected output: True "Coord=(1,1):",// -- Expected output: False "Coord=(1,1)abc",// -- Expected output: False "Coord=(1,1);abc"// -- Expected output: True }; // | this is the important bit Pattern p = Pattern.compile("Coord=\\(\\d,\\d\\)(;|$)"); for (String input: inputs) { Matcher m = p.matcher(input); System.out.printf("%s found? %b%n", input, m.find()); } 

Output

Coord=(1,1) found? true Coord=(1,1); found? true Coord=(1,1): found? false Coord=(1,1)abc found? false Coord=(1,1);abc found? true 
Sign up to request clarification or add additional context in comments.

3 Comments

@AvinashRaj the reason why it matches the last String is because I use find, not matches. Obviously I don't want to be using matches in this context.
yes, it's because of find. But it won't check for the chars present next to ;
@AvinashRaj you are correct, it won't. I don't think that matters here. If I interpret the OP's question correctly, the importance is whether ; is present or not. If so, whichever character follows is irrelevant. If not, the input must end. My interpretation might be wrong though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.