其他教程

其他教程

Products

当前位置:首页 > 其他教程 >

如何迭代“1或多”项的正则表达式?

GG网络技术分享 2025-03-18 16:15 2


问题描述:

I am trying to develop a regular expression to read a pager message into categories. At the end are the responding brigades\' codes (CBORT, CYAND)

These brigade codes represent each responding brigade. The issue is that there can either be one eg. (CBORT) or many eg. (CBAGR, CBORT, CYAND). I am unsure how to make the regex match each brigade as an individual match.

Each brigade code will have the letter C as a prefix.

Can this be done using a regular expression or will I require a PHP script to iterate through the last part of the message to match each of these brigade codes into an array?

Pager Message:

@@ALERT BORT1 G&SC1 GRASS FIRE - SPREADING QUICKLY 79 BOORT-YANDO RD BOORT SVNW 214 J15 (475017) AFPR CBORT CYAND F190400036

Current Regex:

(@@)(ALERT)\\s(\\w+)\\s(\\S+)(C1|C3)\\s(.+)\\s(\\d+|\\d+KM|\\d+ M|CNR|NEAR|NEXT TO|ADJACENT|BEHIND|ACROSS FROM|ACROSS|REAR OF|REAR|OUTSIDE)\\s(.+)\\s(SVNW)\\s(\\d+)\\s(\\w\\d+)\\s((\\d+))\\s(F|AF|FP|AFP|AFPR|AFPRS)\\s(C\\w+)\\s(F\\d+)

The bold section is the section I wish to iterate 1 or many times.

Thank you

网友观点:

You can use ((C\\w+)\\s)+ to have at least one group that match, but capture the following ones as well.

You also need to escape the parenthesis of your message with \\( and \\) (reserved characters)

Full regex :

(@@)(ALERT)\\s(\\w+)\\s(\\S+)(C1|C3)\\s(.+)\\s(\\d+|\\d+KM|\\d+ M|CNR|NEAR|NEXT TO|ADJACENT|BEHIND|ACROSS FROM|ACROSS|REAR OF|REAR|OUTSIDE)\\s(.+)\\s(SVNW)\\s(\\d+)\\s(\\w\\d+)\\s(\\(\\d+\\))\\s(F|AF|FP|AFP|AFPR|AFPRS)\\s((C\\w+)\\s)+(F\\d+)

正则表达式上——基本语法

JavaScript 正则表达式上——基本语法

定义

JavaScript种正则表达式有两种定义方式,定义一个匹配类似 <%XXX%> 的字符串

1. 构造函数

标签:

提交需求或反馈

Demand feedback