如何检查字符串(含URL)是否包含两个指定子串中的任意一个?
检查字符串是否包含两个子串中的任意一个
嘿,这个需求我之前也碰到过,其实核心逻辑很简单:只要目标字符串包含任意一个指定的子串,就返回true,否则返回false。下面给你几种主流编程语言的实用实现方式:
JavaScript 实现
最直接的方式就是用includes()方法配合逻辑或(||),代码清晰易懂:
function checkUrl(url) { return url.includes('localhost') || url.includes('10.0.2.2'); } // 测试你的示例用例 console.log(checkUrl('http://localhost:5000')); // true console.log(checkUrl('10.0.2.2:5000')); // true console.log(checkUrl('dasdasdasdasdlocalhostdasdasd')); // true console.log(checkUrl('dasdasdasd10.0.2.2:5000dasdasd')); // true console.log(checkUrl('http://example.com')); // false
如果需要兼容更老的浏览器(不支持ES6的includes()),可以用indexOf()代替:
function checkUrl(url) { return url.indexOf('localhost') !== -1 || url.indexOf('10.0.2.2') !== -1; }
要是以后需要添加更多子串,用some()方法扩展性更好:
function checkUrl(url) { const targetSubstrings = ['localhost', '10.0.2.2']; return targetSubstrings.some(sub => url.includes(sub)); }
Python 实现
Python的in运算符天生适合做子串判断,配合逻辑或非常简洁:
def check_url(url): return 'localhost' in url or '10.0.2.2' in url # 测试示例 print(check_url('http://localhost:5000')) # True print(check_url('10.0.2.2:5000')) # True print(check_url('dasdasdasdasdlocalhostdasdasd')) # True print(check_url('dasdasdasd10.0.2.2:5000dasdasd')) # True print(check_url('http://example.com')) # False
子串数量多的话,用any()函数更优雅:
def check_url(url): target_substrings = ['localhost', '10.0.2.2'] return any(sub in url for sub in target_substrings)
Java 实现
Java的String.contains()方法可以直接判断子串存在,逻辑或即可满足需求:
public class UrlChecker { public static boolean checkUrl(String url) { return url.contains("localhost") || url.contains("10.0.2.2"); } public static void main(String[] args) { // 测试你的示例 System.out.println(checkUrl("http://localhost:5000")); // true System.out.println(checkUrl("10.0.2.2:5000")); // true System.out.println(checkUrl("dasdasdasdasdlocalhostdasdasd")); // true System.out.println(checkUrl("dasdasdasd10.0.2.2:5000dasdasd")); // true System.out.println(checkUrl("http://example.com")); // false } }
内容的提问来源于stack exchange,提问作者Onyx
相关产品推荐
相关产品推荐

