繁体   English   中英

如何比较忽略几个字符的两个字符串

[英]how to compare two strings ignoring few characters

我想在python中比较两个字符串忽略一些字符,比如字符串是:

"http://localhost:13555/ChessBoard_x16_y20.bmp"

我想忽略字符串中的值"16""20" ; 无论这些值是什么,如果字符串的其余部分与此字符串相同,那么我应该得到结果"TRUE" 我怎样才能做到这一点?

例:

URL = "http://localhost:13555/ChessBoard_x05_y12.bmp"

if URL == "http://localhost:13555/ChessBoard_x16_y16.bmp":
    print("TRUE")
else:
    print("FALSE")

输出:

TRUE

使用正则表达式 这是针对您的情况。 点匹配任何符号。 \\ d匹配一个数字。 必须转义一些特殊符号。

import re
if re.match(r'http://localhost:13555/ChessBoard_x\d\d_y\d\d\.bmp', URL):
    print("TRUE")
else:
    print("FALSE")

也许你可以用正则表达式做到这一点

>>> import re
>>> CHESS_BOARD_PATTERN = r'http://localhost:13555/ChessBoard_x\d+_y\d+.bmp'
>>> def is_chess_board_endpoint(endpoint):
...     return bool(re.match(CHESS_BOARD_PATTERN, endpoint))
... 
>>> is_chess_board_endpoint('http://localhost:13555/ChessBoard_x16_y20.bmp')
True
>>> is_chess_board_endpoint('http://localhost:13555/ChessBoard_x05_y12.bmp')
True
>>> is_chess_board_endpoint('http://google.com.br')
False

但很明显,根据您的解决方案,您必须改进此正则表达式,因为如果您更改主机(例如从localhost更改为192.168.0.10)将无法正常工作。

def checkstrings(string1, string2):
    if len(string1) != len(string2):
        return False
    for x in range(len(string1)):
        if x == 35 or x == 36 or x == 39 or x == 40:
            continue
        if string1[x] != string2[x]:
            return False
    return True

JAVA:

public static boolean checkStrings(String string1, String string2){
        if(string1.length() != string2.length()){
                return false;
        }
        for(int x = 0; x < string1.length(); x++){
                if(x == 35 || x == 36 || x == 39 || x == 40){
                        continue;
                }

                if(string1.charAt(x) != string2.charAt(x)){
                        return false;
                }
        }
        return true;

}

您可以遍历字符串中的字符并检查它们是否为数字。

如果是x.isdigit():

暂无
暂无

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

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