【问题标题】:Check string for certain characters检查字符串中的某些字符
【发布时间】:2017-05-05 07:45:58
【问题描述】:

我收到 2 个字符串作为输入。第一个是名称,第二个是符号。该符号必须正好是 2 个字符。要使符号有效,其字母必须按顺序出现在名称中。 例如 名称:“记事本”和 符号:“Nt”或“Te”有效,但“Et”或“Da”无效。

【问题讨论】:

  • 所以符号不必是紧随其后的正确顺序的 2 个字符?或者为什么 Nt 有效?如果 nt 无效并且只有 No、ot、te 等有效,则可以使用 string.contains() 方法
  • @XtremeBaumer 'Nt' 是有效的,因为 'N' 在 'T' 之前,基本上只要符号中的第二个字母不在第一个之前。

标签: java string validation


【解决方案1】:

您可以构建自己的正则表达式来检查符号是否正确,例如:

String str = "Notepad";
String symbole = "tN";
String regex = "(?i).*";
for(int i = 0; i<symbole.length(); i++){
    regex+=symbole.charAt(i)+".*";
}
System.out.println(str.matches(regex));

例如输出:

Symbole          Regex           Result

tN              (?i).*t.*N.*     false
Nt              (?i).*N.*t.*     true
Nd              (?i).*N.*d.*     true
NeD             (?i).*N.*e.*D.*  true

(?i) 不区分大小写?

Ideone demo

【讨论】:

    【解决方案2】:

    逻辑是——

    • 在字符串中查找“符号的第一个字符”

    • 如果找到,则在first's的索引之后开始的字符串中查找“系统的第二个字符”

    -

    public boolean isValid(String str1, String str2){
        String t1, t2;
        t1 = str1.toLowerCase();
        t2 = str2.toLowerCase();
    
        if( t1.indexOf( t2.charAt(0) ) > -1 )
        if( t1.indexOf( t2.charAt(1), t1.indexOf(t2.charAt(0))) > -1 )
            return true;
    
        return false;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-09
      • 2020-11-01
      • 2014-05-07
      • 2011-03-31
      • 2015-03-15
      • 1970-01-01
      • 2018-04-29
      相关资源
      最近更新 更多