如何用RegEx Tokenize动态拆分含内部项目符号的字符串?
问题解决:动态拆分含内部项目符号的结构化字符串
你需要拆分的原始字符串:
• General The general responsibilities of the role are XYZ • Physical Demands The Physical Demands of this role are XYZ • Education Requirements The education requirements for this role are • Bachelor's Degree • Appropriate Certification • Experience 5 years of experience is required
核心难点是区分作为分组分隔符的「•+标题+3个以上空格」和Education Requirements类别内部的项目符号,要实现动态拆分,可通过以下正则表达式匹配每个分组:
•\s+\w+(?:\s+\w+)*\s{3,}(?:(?!•\s+\w+(?:\s+\w+)*\s{3,}).)*
正则逻辑解释
•\s+\w+(?:\s+\w+)*:匹配分组标题,比如• General、• Education Requirements——以•开头,后跟至少一个空格,再匹配由空格分隔的一个或多个单词(支持多词标题)\s{3,}:严格匹配标题后用于分隔的3个及以上空格,这是区分分组分隔符和内容内部项目符号的关键标志(?:(?!•\s+\w+(?:\s+\w+)*\s{3,}).)*:匹配标题后的所有内容,直到遇到下一个符合「•+标题+3个以上空格」的分组起始标志,自动忽略内容内部的项目符号(比如• Bachelor's Degree),避免误拆分
匹配结果
用上述正则匹配原始字符串,会得到你期望的4个分组:
• General The general responsibilities of the role are XYZ• Physical Demands The Physical Demands of this role are XYZ• Education Requirements The education requirements for this role are • Bachelor's Degree • Appropriate Certification• Experience 5 years of experience is required
适配调整
如果标题包含特殊字符(比如连字符),可以把\w替换成[\w-];如果分隔空格数不是固定3个以上,可调整{3,}为实际需求的数量范围(比如{2,}匹配2个及以上空格)。
内容的提问来源于stack exchange,提问作者Benjamin Stringer
相关产品推荐
相关产品推荐

