当前位置:编程学习 > JAVA >>

JavaScript中两个字符串的匹配

工作中遇到一个问题,两个字符串匹配,要求:每个字符串中最多含有一个*,?可以无限多个

*代表一个任意长度的字符串,而?则代表一个字符

要求可以提示出两个冲突

<input type="text" id="str1"><br>
<input type="text" id="str2"><br>
<input type="button" onclick="checkMarchX()" value="CHECK">
用Javascript实现代码如下:

[javascript] 
function checkMarchX() 
    { 
        var str1 = document.getElementById('str1').value; 
        var str2 = document.getElementById('str2').value; 
        var str1XPosition = str1.indexOf('*'); 
        var str2XPosition = str2.indexOf('*'); 
        if(str1XPosition!=-1 && str2XPosition!=-1)//两者都含有* 
        { 
            var position = str1XPosition>str2XPosition?str2XPosition:str1XPosition;//success 
            if(position!=0) 
            { 
                var patbeforeStr1 = str1.substring(0,position); 
                var patbeforeStr2 = str2.substring(0,position); 
                if(checkMarchQ(patbeforeStr1,patbeforeStr2)) 
                { 
                    //alert(str1+'与'+str2+"前半部分冲突"); 
                    //然后对应后半部分进行测试 
                    var str1XBackPosition = str1.length-str1XPosition-1; 
                    var str2XBackPosition = str2.length-str2XPosition-1; 
                    var backposition = str1XBackPosition>str2XBackPosition?str2XBackPosition:str1XBackPosition; 
                    if (backposition==0) 
                    { 
                        alert(str1+'与'+str2+"冲突"); 
                    } 
                    else 
                    { 
                        var patbackStr1 = str1.substring(str1.length-backposition,str1.length); 
                        var patbackStr2 = str2.substring(str2.length-backposition,str2.length); 
                        if(checkMarchQ(patbackStr1,patbackStr2)) 
                        { 
                            alert(str1+'与'+str2+"冲突"); 
                        } 
                    } 
                } 
            } 
            else 
            { 
                //alert(str1+'与'+str2+"前半部分冲突"); 
                var str1XBackPosition = str1.length-str1XPosition-1; 
                var str2XBackPosition = str2.length-str2XPosition-1; 
                var backposition = str1XBackPosition>str2XBackPosition?str2XBackPosition:str1XBackPosition; 
                if (backposition==0) 
                { 
                    alert(str1+'与'+str2+"冲突"); 
                } 
                else 
                { 
                    var patbackStr1 = str1.substring(str1.length-backposition,str1.length); 
                    var patbackStr2 = str2.substring(str2.length-backposition,str2.length); 
                    if(checkMarchQ(patbackStr1,patbackStr2)) 
                    { 
                        alert(str1+'与'+str2+"冲突"); 
                    } 
                } <

补充:web前端 , JavaScript ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,