You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Swift 4拆分混合英文与阿拉伯语的字符串?

嘿,这个需求其实很好解决,核心就是抓住阿拉伯语和英语的Unicode字符范围差异来做拆分——两种语言的字符在Unicode里属于完全不同的区间,用正则表达式就能精准匹配提取。下面给你具体的实现思路和代码示例:

核心原理
  • 阿拉伯语的核心字符(包括字母、常用标点)主要集中在 U+0600 到 U+06FF 区间,还可以补充一些阿拉伯语专用的扩展字符(比如波斯语阿拉伯字母、特殊标点等)
  • 英语及拉丁系语言的字符则集中在基本拉丁区间 U+0020 到 U+007E(包含空格、常见标点、大小写字母、数字)
Python 实现示例

这是最常用的实现方式,代码简洁易懂:

import re

# 你的混合语言字符串
mixed_string = "بِاسْمِكَ رَبِّي وَضَعْتُ جَنْبِي، وَبِكَ أَرْفَعُهُ، فَإِنْ أَمْسَكْتَ نَفْسِي فَارْحَمْهَا، وَإِنْ أَرْسَلْتَهَا فَاحْفَظْهَا، بِمَا تَحْفَظُ بِهِ عِبَادَكَ الصَّالِحِينَ.Bismika rabbee wadaAAtu janbee wabika arfaAAuh, fa-in amsakta nafsee farhamha, wa-in arsaltaha fahfathha bima tahfathu bihi AAibadakas-saliheen. In Your name my Lord, I lie down and in Your name I rise, so if You should take my soul then have mercy upon it, and if You should return my soul then protect it in the manner You do so with Your righteous servants."

# 匹配阿拉伯语(包含阿拉伯标点、空格)
arabic_regex = re.compile(r'[\u0600-\u06FF\u067E\u0686\u0698\u06D5-\u06DC\u06DE-\u06E8\u06EA-\u06EF\u06FA-\u06FF\s,.؟!]+', re.UNICODE)
arabic_content = ''.join(arabic_regex.findall(mixed_string)).strip()

# 匹配英语(包含拉丁标点、空格、数字)
english_regex = re.compile(r'[a-zA-Z0-9\s,.!?\'"]+', re.UNICODE)
english_content = ''.join(english_regex.findall(mixed_string)).strip()

# 输出结果
print("=== 阿拉伯语部分 ===")
print(arabic_content)
print("\n=== 英语部分 ===")
print(english_content)
JavaScript 实现示例

如果是前端场景,用JS也能轻松实现:

const mixedString = "بِاسْمِكَ رَبِّي وَضَعْتُ جَنْبِي، وَبِكَ أَرْفَعُهُ، فَإِنْ أَمْسَكْتَ نَفْسِي فَارْحَمْهَا، وَإِنْ أَرْسَلْتَهَا فَاحْفَظْهَا، بِمَا تَحْفَظُ بِهِ عِبَادَكَ الصَّالِحِينَ.Bismika rabbee wadaAAtu janbee wabika arfaAAuh, fa-in amsakta nafsee farhamha, wa-in arsaltaha fahfathha bima tahfathu bihi AAibadakas-saliheen. In Your name my Lord, I lie down and in Your name I rise, so if You should take my soul then have mercy upon it, and if You should return my soul then protect it in the manner You do so with Your righteous servants.";

// 提取阿拉伯语
const arabicContent = mixedString.match(/[\u0600-\u06FF\u067E\u0686\u0698\u06D5-\u06DC\u06DE-\u06E8\u06EA-\u06EF\u06FA-\u06FF\s,.؟!]+/g).join('').trim();

// 提取英语
const englishContent = mixedString.match(/[a-zA-Z0-9\s,.!?\'"]+/g).join('').trim();

console.log("=== 阿拉伯语部分 ===");
console.log(arabicContent);
console.log("\n=== 英语部分 ===");
console.log(englishContent);
注意事项
  • 如果你的字符串里有其他特殊字符(比如阿拉伯语的装饰符号、英语的特殊符号),可以把对应的Unicode区间加到正则表达式里
  • 测试时要注意边界情况:比如两种语言的标点相邻(像示例里的阿拉伯语句号紧跟英语单词),正则会自动区分开
  • 如果需要支持更多语言,只需要扩展对应的Unicode区间即可

内容的提问来源于stack exchange,提问作者A.s.ALI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:35:47