1

I need to search for the first occurrence of text between single quotes, return the text (without the quotes), but if there is no quoted text is found, return null. I cannot use any additional methods. For example:

  1. On input "this is some 'text' and some 'additional text'" the method should return: text
  2. On input "this is an empty string '' and another 'string'" it should return: nothing.

My code:


    public static String findSingleQuotedTextSimple(String input) {
        Pattern pattern = Pattern.compile ("(?:^|\\s)'([^']*?)'(?:$|\\s)");
        Matcher matcher = pattern.matcher (input);
        if (matcher.find()) {
            return (matcher.group ());
        }
        else {
            return null;
        }
    }

However I seem to fail the test and the output is null every time, please help me point out the problem.

Rika
  • 75
  • 3
  • Your code works after [you use](https://ideone.com/QfaFTc) `matcher.group(1)` – Wiktor Stribiżew Dec 26 '19 at 17:19
  • for this tester it fails, and I don't understand why: `String[] inputs = {"fdsaf'test'fdsafdsa", "'onetwothree'fourfive", "abc'def'xyz'123'", "more'testing", "''", "'", "another''test" }; String[] expect = {"test", "onetwothree", "def", null, "", null, "" }; for (int i = 0; i < inputs.length; ++i) { String output = RegexpPractice.findSingleQuotedTextSimple(inputs[i]); assertEquals(expect[i], output); }` – Rika Dec 26 '19 at 17:26
  • `(?:^|\\s)` matches a start of a string position or whitespace. Remove these parts from your regex if you do not intend to match these. – Wiktor Stribiżew Dec 26 '19 at 17:29
  • `I cannot use any additional methods.` What does that mean ? You should state that this regex is not something you created and ask how to fix it. From the comment `"more'testing", "''", "'", "another''test"` makes this quite obvious. –  Dec 26 '19 at 20:12

0 Answers0