【问题标题】:a regular expression for substring or exact match子字符串或完全匹配的正则表达式
【发布时间】:2015-04-01 02:40:58
【问题描述】:

给定示例字符串“hello”,我需要一个表达式来验证用户输入(现有字母的任意组合;不重复使用过的字母)。

在此上下文中有效和无效的输入示例如下:

有效:“hello”、“hell”、“lol”……等

无效:“heel”、“loo”...等

我已经尝试过...

(.)*([hello])(.)*

[hello]+

但是,它们不会对无效的进行排序。

任何帮助将不胜感激。

注意:这不仅仅是子字符串或完全匹配,根据示例,字母组合是有效的。

【问题讨论】:

  • 为什么lol 是一个有效的条目?
  • 我希望用户能够从给定的字母组合中创建任何单词
  • 解释有效和无效答案的变化并加强语言以提供完整的问题。

标签: java regex string


【解决方案1】:

正则表达式不是正确的工具...它们应该用于从左到右匹配,而不是按随机顺序计算各种字符。你最好有一个验证字符串hello,遍历输入字符串中的每个字符,并检查该字符是否存在(如果存在,从验证字符串中删除该字符并继续。否则,输入失败)。

这是quick example I whipped up in Java

public static boolean testString(String testString)
{
    String allowedCharacters = "hello";

    for(int i = 0; i < testString.length(); i++) {
        int position = allowedCharacters.indexOf(testString.charAt(i));

        if(position == -1) {
            System.out.println(testString + " - fail");
            return false;
        } else {
            allowedCharacters = allowedCharacters.substring(0, position)
                              + allowedCharacters.substring(position + 1);
        }
    }


    System.out.println(testString + " - success");
    return true;
}

使用示例输出调用函数:

testString("hello"); // hello - success
testString("hell");  // hell - success
testString("lol");   // lol - success

testString("heel");  // heel - fail
testString("loo");   // loo - fail

【讨论】:

  • 非常感谢山姆,我希望能有一个简短的小表情。我有一个与您非常相似的解决方案,所以我想我会保持原样。再次感谢您的意见
  • 这可以通过表达式实现,但不会很短。并且可能会变得非常低效以及让开发人员阅读/编辑感到困惑。我会坚持使用您正在使用的可重用功能:)
  • 谢谢山姆,会做的:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
  • 2022-07-11
相关资源
最近更新 更多