For example :
String s= "Hello every one !! ";
Now I want to check if the string does not starts with
Hello
Hi
Hey
Then return true ?
For example :
String s= "Hello every one !! ";
Now I want to check if the string does not starts with
Hello
Hi
Hey
Then return true ?
You can use Negative Lookahead in regex like this:
This is for JavaScript
/^(?!Hello|Hi|Hey).+/gm
will match 4 and 8 line below
^ - starting the line
(?! ) - starting at the current position in the expression, ensures that the given pattern will not match. Does not consume characters. In you case "Hello" or "Hi" or "Hey" with expression Hello|Hi|Hey which means: matches the characters Hello literally (case sensitive) or matches the characters Hi literally (case sensitive) or matches the characters Hey literally (case sensitive)
.+ - matches any character (except newline) between one and unlimited times, as many times as possible, e.g. whole
m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string) (in case of matching string it is not necessary)
g modifier: global. All matches (don't return on first match) (in case of matching string it is not necessary too)
P.S. You can use bit shorter version
/^(?!H(ello|i|ey)).+/gm
P.P.S. These examples works also for Ruby, Python and PHP
Intentionally with regex, it would be:
^(Hello|Hi|Hey)
And assuming you want in Java (with above regex):
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
System.out.println("If it is case sensitive:\n");
String[] strings = new String[] {
"Hello world!", "Hi world!", "Hey world!",
" Hello world!", " Hi world!", " Hey world!",
"hello world!", "hi world!", "hey world!" };
for (String string : strings) {
Pattern pattern = Pattern.compile("^(Hello|Hi|Hey)");
Matcher matcher = pattern.matcher(string);
System.out.println(string + " ==> "
+ (!matcher.find() ? "ok" : "not ok"));
}
System.out.println("\nIf it is case insensitive:\n");
for (String string : strings) {
Pattern pattern = Pattern.compile("^(Hello|Hi|Hey)",
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(string);
System.out.println(string + " ==> "
+ (!matcher.find() ? "ok" : "not ok"));
}
}
}
This only demonstrates how regex pattern matcher works in Java.
To make it to a method which returns a boolean value, try by yourself.
The following regular expression returns true if the string does not start with any of the words you listed.
\A(?!Hello|Hi|Hey).*?{1}
The way this works is
\A - checks if 'Hello' is the start of string
!? - is a negative lookahead and I think it is supported in all regexp implementations
((Hello|Hi|Hey).*?){1} - matches one of the words separated by the | symbol
Once we find a match of the words, we are doing a negative lookahead to implement the 'does not match' logic.