【问题标题】:Regex Pattern for a string not starting with a couple of given words [duplicate]不以几个给定单词开头的字符串的正则表达式模式[重复]
【发布时间】:2015-09-18 12:06:18
【问题描述】:

例如:

String s= "Hello every one !! ";

现在我想检查字符串是否不以

开头
Hello 
Hi
Hey

然后返回真?

【问题讨论】:

  • 欢迎来到 Stack Overflow!请展示您到目前为止所做的尝试以及您得到的结果或错误。
  • 如果是Java,可以不用String.contains吗?
  • 在询问正则表达式问题时,请指定语言。因为您有 ;和关键字字符串,我假设它是Java。否则请告诉我们
  • 假设是Java,可以使用String.startsWith("Hi")

标签: regex


【解决方案1】:

您可以像这样在正则表达式中使用Negative Lookahead

这是用于 JavaScript 的

/^(?!Hello|Hi|Hey).+/gm

将匹配下面的 4 和 8 行

  1. 大家好!!
  2. 嗨,我的钥匙茶馆
  3. 嘿,我的钥匙茶馆
  4. 也许我的主要茶馆
  5. 大家好!!
  6. 嗨,我的钥匙茶馆
  7. 嘿,我的钥匙茶馆
  8. 也许是我的 asdf 重点茶馆

^ - 开始行

(?!) - 从表达式中的当前位置开始,确保给定的模式不会匹配。不消耗字符。 在你的情况下,“Hello”或“Hi”或“Hey”带有表达式Hello|Hi|Hey,这意味着:匹配字符Hello(区分大小写)从字面上匹配字符 Hi(区分大小写)从字面上匹配字符 Hey(区分大小写)

.+ - 匹配任何字符(换行符除外)一次到无限次,尽可能多次,例如整个

m 修饰符:多行。使 ^ 和 $ 匹配每行的开始/结束(不仅是字符串的开始/结束)(如果匹配字符串,则不需要

g 修饰符:全局。所有匹配项(第一次匹配时不返回)(如果匹配字符串也不需要

附:你可以使用更短的版本

/^(?!H(ello|i|ey)).+/gm

附言这些示例也适用于 Ruby、Python 和 PHP

【讨论】:

    【解决方案2】:

    故意使用正则表达式,它将是:

    ^(Hello|Hi|Hey)
    

    假设你想要在 Java 中(使用上面的正则表达式):

    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"));
        }
    }
    
    }
    

    这仅演示了正则表达式模式匹配器在 Java 中的工作原理。

    要使其成为返回布尔值的方法,请自行尝试。

    【讨论】:

    • 只是一个警告,这可能区分大小写。
    【解决方案3】:

    如果字符串不以您列出的任何单词开头,则以下正则表达式返回 true。

    \A(?!Hello|Hi|Hey).*?{1}
    

    它的工作方式是

    \A - 检查 'Hello' 是否是字符串的开头

    !? - 是一个负前瞻,我认为它在所有正则表达式实现中都受支持

    ((Hello|Hi|Hey).*?){1} - 匹配由 | 分隔的单词之一符号

    一旦我们找到匹配的单词,我们就会进行否定的前瞻来实现“不匹配”逻辑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      • 1970-01-01
      • 2015-06-24
      • 1970-01-01
      • 2013-11-23
      • 2018-09-07
      • 2023-03-15
      相关资源
      最近更新 更多