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

如何使用正则表达式从NOAA/NWS天气预警中单独提取*开头项目

问题原因

你原来的正则使用了贪婪匹配逻辑,\X*会尽可能多的匹配字符,因此会跨多个条目一直匹配到最后一处符合双换行规则的位置,无法拆分单个*开头的独立条目。

解决方案

可以使用非贪婪匹配+正向预查的规则实现需求,通用兼容大部分正则引擎的写法如下:

/\*[\s\S]*?(?=\n{2}|\Z)/g

各部分含义:

  • \*:匹配条目开头的星号
  • [\s\S]*?:非贪婪匹配任意字符(包含换行符,比\X的兼容性更好),尽可能少的匹配内容
  • (?=\n{2}|\Z):正向预查,匹配到两个连续换行或者文本结束的位置就停止,不会把分隔用的双换行符包含到匹配结果中,同时不会漏掉最后一个没有后续双换行的条目

如果你的正则引擎支持单行模式(s修饰符),也可以简化为:

/\*.*?(?=\n{2}|\Z)/gs

代码示例(Python)

import re

# 你的测试文本
test_content = """...FLASH FLOOD WATCH REMAINS IN EFFECT UNTIL 7 AM AKDT THIS 
MORNING... 
The Flash Flood Watch continues for: 
 
* Including the following area, Cape Decision to Salisbury Sound 
Coastal Area. 
 
* Until 7 AM AKDT this morning. 
 
* The low tracked inland over the northeast gulf coast early 
Saturday morning. This storm produced 48 hour rain amounts ranging 
from 2 to 4 inches with possible localized higher amounts. Locally 
heavy showers will spread onshore through Saturday morning. 
Antecedent soil moisture values are similar to last October which 
produced landslides in the Sitka area. 
 
* Associated with the moderate to heavy rainfall, high winds will 
increase the risk of isolated landslides in prone areas late 
Friday afternoon into Friday night. There will be sharp rises on 
small streams through Friday with potential flooding by Saturday 
morning.
"""

# 匹配所有独立条目
raw_items = re.findall(r'\*[\s\S]*?(?=\n{2}|\Z)', test_content)
# 去除条目内部多余的换行和空格,合并为单行
processed_items = [re.sub(r'\n\s*', ' ', item.strip()) for item in raw_items]

# 输出结果
for item in processed_items:
    print(item)

输出效果

* Including the following area, Cape Decision to Salisbury Sound Coastal Area.
* Until 7 AM AKDT this morning.
* The low tracked inland over the northeast gulf coast early Saturday morning. This storm produced 48 hour rain amounts ranging from 2 to 4 inches with possible localized higher amounts. Locally heavy showers will spread onshore through Saturday morning. Antecedent soil moisture values are similar to last October which produced landslides in the Sitka area.
* Associated with the moderate to heavy rainfall, high winds will increase the risk of isolated landslides in prone areas late Friday afternoon into Friday night. There will be sharp rises on small streams through Friday with potential flooding by Saturday morning.

内容的提问来源于stack exchange,提问作者Tony Mauro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:57:01