简体   繁体   English

子字符串或完全匹配的正则表达式

[英]a regular expression for substring or exact match

Given the example string "hello", I need an expression for validating user input (any combination of the existing letters; without repeating a used letter). 给定示例字符串“ hello”,我需要一个表达式来验证用户输入(现有字母的任何组合;不重复使用的字母)。

In this context valid and invalid input examples are as follows: 在这种情况下,有效和无效的输入示例如下:

valid: "hello", "hell", "lol" .... etc. 有效:“ hello”,“ hell”,“ lol” ....等

invalid: "heel", "loo"... etc. 无效:“脚跟”,“厕所” ...等。

I have tried the likes of ... 我尝试过...

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

and

[hello]+

But, they don't sort the invalid ones. 但是,它们不会对无效的排序。

Any help would be appreciated thank you. 任何帮助将不胜感激,谢谢。

NOTE: This is not just substring or exact match, per the examples, combinations of letters are valid. 注意:这不仅是子字符串或完全匹配,根据示例,字母组合也是有效的。

Regular expressions is not the right tool...they should be used for matching left to right, not counting various characters in a random order. 正则表达式不是正确的工具...应将其用于从左到右匹配,而不是以随机顺序计算各种字符。 You're better off having a validation string hello , looping through each character from the input string, and checking to see if the character exists (if it does, remove that character from the validation string and continue. otherwise, the input fails). 您最好拥有一个验证字符串hello ,循环遍历输入字符串中的每个字符,并检查该字符是否存在(如果存在,请从验证字符串中删除该字符,然后继续。否则,输入将失败)。

Here is a quick example I whipped up in Java : 这是我用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;
}

Calling the function with example output: 调用带有示例输出的函数:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM