简体   繁体   English

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

[英]how to compare two strings ignoring few characters

I want to compare two strings in python ignoring some characters, like if the string is: 我想在python中比较两个字符串忽略一些字符,比如字符串是:

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

I want to ignore the values "16" and "20" in the string; 我想忽略字符串中的值"16""20" ; no matter what these values are, if the rest of the string is same as this string is then I should get the result "TRUE" . 无论这些值是什么,如果字符串的其余部分与此字符串相同,那么我应该得到结果"TRUE" How can I do this? 我怎样才能做到这一点?

Example: 例:

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

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

Output: 输出:

TRUE

Use regular expressions . 使用正则表达式 Here it is for your case. 这是针对您的情况。 A dot matches any symbol. 点匹配任何符号。 A \\d matches a digit. \\ d匹配一个数字。 Some special symbols have to be escaped. 必须转义一些特殊符号。

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

Maybe you will be able to do this with regex 也许你可以用正则表达式做到这一点

>>> 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

But it is obvious that depending on your solution, you have to improve this regex, because if you change the host (from localhost to 192.168.0.10 for example) will not work. 但很明显,根据您的解决方案,您必须改进此正则表达式,因为如果您更改主机(例如从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: 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;

}

You can loop through characters in the string and check if they are digits or not. 您可以遍历字符串中的字符并检查它们是否为数字。 Ie

if x.isdigit(): 如果是x.isdigit():

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

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