-1

I am using regex in java, and I cannot create a regex to match what I want it to. I want to match everything in a string that begins and ends with a character.

"cats-are-cute" should match and return cats-are-cute

!!!DOG-CAT!!! should match and return DOG-CAT

I am using https://regexr.com/ to test, and it says my regex should work

I'm not even sure how I should attempt to fix this. I've found out that it will quite if the very first character does not match (e.i it is a special character) but it will match if the entire string begins + ends with a matching character.

It will not match if a special character begins or ends the entire string

Here is my code:

    Pattern pattern = Pattern.compile("([A-Za-z0-9].*[A-Za-z0-9])");
    Matcher matcher = pattern.matcher(word);
    if(matcher.matches())
    {
        System.out.println("Matches");
        System.out.println(matcher.start());
        System.out.println(matcher.end());
    }


if I type testing it returns

Matches
0
7

Small question: why is it 7 and not 6?

just like it should but if I do "testing" matcher.matches() is false. I think it should output

Matches
1
7

but sadly it does not as matcher.matches() returns false. I think my regex is working, because quite a few sites have said that my regex will match what I want it to. Am I missing something with Matcher matches()? Does it not do what I think it does?

  • 1
    As the documentation of `Matcher.matches` states it *Attempts to match the entire region against the pattern.*. You need to use `Matcher.find` if you don't want your entire String to be matched. – OH GOD SPIDERS Sep 12 '19 at 16:39
  • >.< dang I'm not very smart are I? Edit: That worked, thank you so much! – Michael Cabatingan Sep 12 '19 at 16:40

1 Answers1

-1

I just needed to use find instead of matches, as OH GOD SPIDERS suggested in this comment:

As the documentation of Matcher.matches states it Attempts to match the entire region against the pattern.. You need to use Matcher.find if you don't want your entire String to be matched.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92