其他教程

其他教程

Products

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

如何在Go中进行可选的正则表达式匹配

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


问题描述:

Say I have the following two types of string inputs:

1) \"feat: this is a feature\"

2) \"feat[JIRA-xxxx]: this is Jira feature

The strings contains three parts, there feat is Type, JIRA-xxx inside [] is optional Jira story id, and rest part after : is subject.

I want to use a single regexp to match the three parts, optional file should get nil if not present. The following is my code:

var re *regexp.Regexp

re = regexp.MustCompile(\"^(\\\\w*)(\\\\[(.*)\\\\])?\\\\:\\\\s(.*)$\")

input := \"feat[JIRA-xxxx]: this is Jira feature\"

res := re.FindAllStringSubmatch(input, -1)

fmt.Print(\"%q\", res)

My regular expression has a problem. Because the Jira ID part is optional, I have to use ()?, but () has the other meaning of returning matched value, so with my code, it returns four matches:

`feat`, `[JIRA-xxx]`, JIRA-xxx`, `this is Jira feature`

How to modify the expression so that I get only the intended 3 matches?

图片转代码服务由CSDN问答提供

感谢您的意见,我们尽快改进~

功能建议

说我有以下两种类型的字符串输入:</ p>

  1)“壮举:这是一个功能” 

2)“壮举[JIRA-xxxx]:这是吉拉功能

</ code> </ pre>

字符串包含三个部分, feat </ code>是Type, [] </ code>中的 JIRA-xxx </ code>是可选的Jira故事ID,其余部分在:</ code>之后是 </ p>

我想使用一个正则表达式来匹配这三个部分,如果不存在则可选文件应该为nil。以下是我的代码:</ p>

< pre> var re * regexp.Regexp

re = regexp.MustCompile(“ ^(\\\\ w *)(\\\\ [(。*)\\\\]]?\\\\:\\\\ s(。*)$ “)

input:=” feat [JIRA-xxxx]:这是Jira功能“

res:= re.FindAllStringSubmatch(input,-1)

fmt.Print(”%q“,res)

</ code> </ pre>

我的正则表达式有问题,因为Jira ID部分是可选的,所以我必须使用()?</ code>,但是要使用()< / code>的其他含义是返回匹配的值,因此对于我的代码,它返回四个匹配项:</ p>

 `feat`,[[JIRA-xxx]`,JIRA-xxx`,\'这是Jira功能\'

</ code> </ pre>

如何 修改表达式,以便只得到预期的3个匹配项?</ p>

</ div>

网友观点:

Use the ?: modifier to create a non capturing group:

re = regexp.MustCompile(\\\"^(\\\\w*)(?:\\\\[(.*)\\\\])?\\\\:\\\\s(.*)$\\\")

Run it on the playground.

正则表达式匹配:进阶版

经典正则表达式问题

给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 '.' 和 '' 的正则表达式匹配。 '.' 匹配任意单个字符 '' 匹配零个或多个元素

通常该问题的求解采取动态规划,即dp[i][j]表示s的前i部分,与p串的前j部分是否能够匹配。

每次研究s[i]与p[j]的匹配情况完成 dp[][]数组的迭代填充,注意初始化dp[0][0] = true

进阶问题

给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 '.' 和 '' 的正则表达式匹配。 '.' 匹配任意单个字符 '' 匹配零个或多个前面的那一个元素

问题修改为前面那个元素,因此需要特别考虑*的情况。 容易知道匹配过程包含三种:

s[i-1]==p[j-1] || p[j-1]=='.' 此时dp[i][j]取决于前面部分的匹配结果,即: dp[i-1][j-1]
p[j-1]=='*' 此时需要考察*的前部分,若为普通字母,那可以分为三小类:
其一,匹配0个,即dp[i][j-2]能够完成匹配,那么此时可以通过匹配0个,使得dp[i][j] = true 其二,匹配1个,即dp[i][j-1]能够匹配,其隐含意思是s[i-1]==p[j-2] 那么通过匹配一个,可以使得dp[i][j]=true 其三,匹配多个,其需要研究p[j-2]==s[i-1] 并且 dp[i-1][j]==true 即需要s串为最后两个为相同,并且和p串末尾匹配


在这里插入图片描述

特殊情况

若出现 “.*”的情况,那么这两个字符可以表示任意串,那么使得dp[i][j]=true的情况,可以为p的前面j-2部分与 s串的任意前缀部分匹配即可。
因此出现该情况时,只需要遍历 dp[k][j-2]即可(其中k<=i),一旦出现true,那么满足

代码实现

标签:

提交需求或反馈

Demand feedback