如何解析指定URL字符串提取数值26并存入变量?
提取URL中的订单ID(数值26)的实现方法
以下是几种主流编程语言的具体实现方案:
Python实现
- 正则表达式匹配法
import re url = "https://20.85.239.243:50000/b1s/v1/Orders(26)" match_result = re.search(r'\((\d+)\)', url) if match_result: order_id = int(match_result.group(1)) # 此时order_id变量存储数值26
- 字符串分割法
url = "https://20.85.239.243:50000/b1s/v1/Orders(26)" order_id = int(url.split('(')[1].split(')')[0]) # 此时order_id变量存储数值26
JavaScript实现
- 正则表达式匹配法
const url = "https://20.85.239.243:50000/b1s/v1/Orders(26)"; const matchResult = url.match(/\((\d+)\)/); if (matchResult) { const orderId = parseInt(matchResult[1], 10); // 此时orderId变量存储数值26 }
- 字符串截取法
const url = "https://20.85.239.243:50000/b1s/v1/Orders(26)"; const startIndex = url.indexOf('(') + 1; const endIndex = url.indexOf(')'); const orderId = parseInt(url.slice(startIndex, endIndex), 10); // 此时orderId变量存储数值26
Java实现
- 正则表达式匹配法
import java.util.regex.Matcher; import java.util.regex.Pattern; public class UrlParser { public static void main(String[] args) { String url = "https://20.85.239.243:50000/b1s/v1/Orders(26)"; Pattern pattern = Pattern.compile("\\((\\d+)\\)"); Matcher matcher = pattern.matcher(url); if (matcher.find()) { int orderId = Integer.parseInt(matcher.group(1)); // 此时orderId变量存储数值26 } } }
- 字符串分割法
public class UrlParser { public static void main(String[] args) { String url = "https://20.85.239.243:50000/b1s/v1/Orders(26)"; String[] splitByLeftParen = url.split("\\("); String[] splitByRightParen = splitByLeftParen[1].split("\\)"); int orderId = Integer.parseInt(splitByRightParen[0]); // 此时orderId变量存储数值26 } }
内容的提问来源于stack exchange,提问作者Andres Edu
相关产品推荐
相关产品推荐

