使用正则表达式捕获字符串内的组

时间:2022-11-09 20:16:05

i dont know much about regular expressions and from what i'v learned i cant solve my entire problem.

我不太了解正则表达式,从我学到的东西我无法解决我的整个问题。

I have this String:

我有这个字符串:

04 credits between subjects of block 02

02区块的主题之间有04学分

I'm only sure i will have [00-99] on the beggining and at end.

我只相信我会在开始时有[00-99]。

I wanna capture the beggining and the end IF the middle has "credits between", the system can have other formats as input, so i wanna be sure that these fields captured will go from the correct pattern.

我想捕获开始和结束如果中间有“信用之间”,系统可以有其他格式作为输入,所以我想确保捕获的这些字段将来自正确的模式。

This is what i'v tried to do:

这就是我试图做的事情:

(\w\w) ^credits between$.+ (\w\w)

I'm using the Regexr website to see what i'm doing, but no success.

我正在使用Regexr网站查看我在做什么,但没有成功。

1 个解决方案

#1


2  

You may use the following regex:

您可以使用以下正则表达式:

^(\d{2})\b.*credits between.*\b(\d{2})$

See regex demo

请参阅正则表达式演示

It will match and capture 2 digits at the beginning and end if the string itself contains credits between. Note that newlines can be supported with [\s\S] instead of ..

如果字符串本身包含信用,它将匹配并捕获开头和结尾的2位数字。请注意,可以使用[\ s \ S]而不是..来支持换行符。

The word boundaries \b just make the engine match the digits followed by a non-word character (you may remove it if that is not expected behavior). Then, you'd need to use ^(\d{2})\b.*credits between.*?(\d{2})$ with the lazy matching .*? at the end.

单词boundary \ b只是使引擎匹配数字后跟非单词字符(如果不是预期的行为,你可以删除它)。然后,你需要在。*?(\ d {2})$之间使用^(\ d {2})\ b。*信用与懒惰匹配。*?最后。

If the number of digits in the numbers at both ends can vary, just use

如果两端数字的位数可以变化,只需使用

^(\d+).*credits between.*?(\d+)$

See another demo

看另一个演示

#1


2  

You may use the following regex:

您可以使用以下正则表达式:

^(\d{2})\b.*credits between.*\b(\d{2})$

See regex demo

请参阅正则表达式演示

It will match and capture 2 digits at the beginning and end if the string itself contains credits between. Note that newlines can be supported with [\s\S] instead of ..

如果字符串本身包含信用,它将匹配并捕获开头和结尾的2位数字。请注意,可以使用[\ s \ S]而不是..来支持换行符。

The word boundaries \b just make the engine match the digits followed by a non-word character (you may remove it if that is not expected behavior). Then, you'd need to use ^(\d{2})\b.*credits between.*?(\d{2})$ with the lazy matching .*? at the end.

单词boundary \ b只是使引擎匹配数字后跟非单词字符(如果不是预期的行为,你可以删除它)。然后,你需要在。*?(\ d {2})$之间使用^(\ d {2})\ b。*信用与懒惰匹配。*?最后。

If the number of digits in the numbers at both ends can vary, just use

如果两端数字的位数可以变化,只需使用

^(\d+).*credits between.*?(\d+)$

See another demo

看另一个演示