【问题标题】:Rexexp to match all the numbers,alphabets,special characters in a string正则表达式匹配字符串中的所有数字、字母、特殊字符
【发布时间】:2014-10-30 02:50:49
【问题描述】:

我想要一个模式来匹配包含所有内容的字符串(字母、数字、特殊字符)

public static void main(String[] args) {

  String retVal=null;

    try
    {
        String s1 = "[0-9a-zA-Z].*:[0-9a-zA-Z].*:(.*):[0-9a-zA-Z].*";
        String s2 = "BNTPSDAE31G:BNTPSDAE:Healthcheck:Major";

        Pattern pattern = null;


        //if ( ! StringUtils.isEmpty(s1) )
        if ( ( s1 != null ) && ( ! s1.matches("\\s*") ) )
        {
                pattern = Pattern.compile(s1);
        }

        //if ( ! StringUtils.isEmpty(s2) )
        if ( s2 != null )
        {
            Matcher matcher = pattern.matcher( s2 );
            if ( matcher.matches() )
            {
                retVal = matcher.group(1);

                // A special case/kludge for Asentria. Temp alarms contain "Normal/High" etc.
                // Switch Normal to return CLEAR. The default for this usage will be RAISE.
                // Need to handle switches in XML. This won't work if anyone puts "normal" in their event alias.
                if ("Restore".equalsIgnoreCase ( retVal ) )
                {

                }

            }
        }
    }

    catch( Exception e )
    {
        System.out.println("Error evaluating args : " );
    }
     System.out.println("retVal------"+retVal);

}

输出是: 健康检查 Hera 使用这个 [0-9a-zA-Z].* 只匹配字母和数字,但如果字符串也有特殊字符,我想匹配它

非常感谢任何帮助

【问题讨论】:

  • 什么是不允许的?我对这个问题有点困惑。你能帮我多理解一点吗...

标签: regex


【解决方案1】:

试试这个:

如果你想匹配单个元素,试试这个:

2.1.2 :001 > s = "asad3435@#:$%adasd1213"
2.1.2 :008 > s.scan(/./)
 => ["a", "s", "a", "d", "3", "4", "3", "5", "@", "#", ":", "$", "%", "a", "d", "a", "s", "d", "1", "2", "1", "3"] 

或者你想一次全部匹配试试这个:

2.1.2 :009 > s.scan(/[^.]+/)
 => ["asad3435@#:$%adasd1213"] 

【讨论】:

    【解决方案2】:

    试试下面的正则表达式,它对我有用:)

    [^:]+
    

    您可能需要在其上放置一个全局修饰符以使其匹配所有字符串。

    【讨论】:

      猜你喜欢
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多