1

I am stuck in a simple issue I want to check if any of the words : he, be, de is present my text.

So I created the pattern (present in the code) using '|' to symbolize OR and then I matched against my text. But the match is giving me false result (in print statement).

I tried to do the same match in Notepad++ using Regex search and it worked there but gives FALSE( no match) in Java. C

public class Del {
    public static void main(String[] args) {
        String pattern="he|be|de";
        String text= "he is ";
        System.out.println(text.matches(pattern));
    }
}

Can any one suggest what am I doing wrong. Thanks

Geek
  • 627
  • 1
  • 8
  • 18
  • 1
    `String.matches(regex)` checks the entire string for a match, not just the beginning. – Beefster Dec 18 '17 at 22:47
  • 1
    The `matches` method try to match the entire string, not a part of the string. – Casimir et Hippolyte Dec 18 '17 at 22:48
  • 1
    You can also use `[hbd]e` (but, again, not with `matches`). Be warned: you must add word delimiters as well, else it will match (I mean 'find') the `he` in `bobshebob` and the `de` in the `dipdedipdedap`. – Jongware Dec 18 '17 at 22:49
  • 1
    HI @usr2564301, why do you say it is duplicate. A person who is trying to match a text to the pattern how will he conclude that I should look for 'find' v/s matches difference. – Geek Dec 18 '17 at 22:52
  • ? Because it answers this question? All I had to do was search for `java match regex`; this Stack Overflow answer came out in the top. – Jongware Dec 18 '17 at 22:53

2 Answers2

2

It's because you are trying to match against the entire string instead of the part to find. For example, this code will find that only a part of the string is conforming to the present regex:

Matcher m = Pattern.compile("he|be|de").matcher("he is ");
m.find(); //true

When you want to match an entire string and check if that string contains he|be|de use this regex .*(he|be|de).*

. means any symbol, * is previous symbol may be present zero or more times. Example:

"he is ".matches(".*(he|be|de).*"); //true
Dimitar
  • 4,402
  • 4
  • 31
  • 47
fxrbfg
  • 1,756
  • 1
  • 11
  • 17
-1
    String regExp="he|be|de";
    Pattern pattern = Pattern.compile(regExp);   
    String text = "he is ";
    Matcher matcher = pattern.matcher(text);
    System.out.println(matcher.find()); 
nitishk72
  • 1,616
  • 3
  • 12
  • 21