其他教程

其他教程

Products

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

正则表达式在两个特定正斜杠之间提取字符串

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


问题描述:

Hi I have the following text:

file:/home/dx/reader/validation-garage/IDON/test-test-test@2016-10-04.txt#/

I need to retrieve test-test-test@2016-10-04.txt# from the string above. If I can also exclude the hash even better.

I\'ve tried looking at examples like this Regex to find text between second and third slashes but having trouble getting it working, can anyone help?

I\'m using PHP regex to do this.

网友观点:

You may try regex expression below

\\/([a-z\\-]*\\@[0-9\\-\\.]*[a-z]{3}\\#)\\/

A working example is here: https://www.regex101.com/r/RYsh7H/1

Explanation:

[a-z\\-]* => Matches test-test-test part with lowercase and can contain dahses

\\@ => Matches constant @ sign

[0-9\\-\\.]* => Matches the file name with digits, dashes and {dot}

[a-z]{3}\\# => Matches your 3 letter extension and #

PS: If you really do not need # you do not have to use regex. And you may consider using parse_url method of PHP.

Hope this helps;

Without regex you can do:

$url_parts = parse_url(\'file:/home/dx/reader/validation-garage/IDON/test-test-test@2016-10-04.txt#/\');

echo end(explode(\'/\', $url_parts[\'path\']));

or better:

$url_path = parse_url(\'file:/home/dx/reader/validation-garage/IDON/test-test-test@2016-10-04.txt#/\', PHP_URL_PATH);

echo end(explode(\'/\', $url_path));

basename() also works, so you can also do like this:

echo basename(\'file:/home/dx/reader/validation-garage/IDON/test-test-test@2016-10-04.txt#/\');

正则表达式提取公式RegexString()

公式名称:RegexString(Text,Rule,Advance,Index)

用途说明:在Excel表格或WPS表格中,使用正在表达式公式RegexString(Text,Rule,Advance,Inde)从一段文本中提取需要的字符(数据)。

参数说明:参数Text指原始文本;Rule指正则表达式匹配规则,这里使用的是C#.NET支持的正则表达式规则;Advance指是否是高级模式,0表示默认,1表示使用高级模式,即直接输入正则表达式;Index指当匹配结果多个时按顺序返回给定序号(索引)的值,默认为0,表示返回全部,填N表示返回结果中第N个值,如果N大于结果中的数量,则返回最后一个值。

数据来源:本地

运行环境:Excel2007及以上,WPS2019及以上

如下图所示,书写公式=RegexString($H$2,"value=\\""([A-Z]+)\\"">([\\u4e00-\\u9fa5]{1,})",1,G3)从单元格H2中查找币种代码。单元格H2的内容是一段网页源代码,规律是“value="币种代码">币种名称”。

如下图所示,书写公式=RegexString($H$2,"value=\\""[A-Z]+\\"">([\\u4e00-\\u9fa5]{1,})",1,G3)从单元格H2中查找币种名称。单元格H2的内容是一段网页源代码,规律是“value="币种代码">币种名称”。

要点说明

  • 正则表达式([A-Z]+)表示匹配一个以上的大写字母,这里用来匹配币种代码,其中括号()表示要返回的结果,括号外的数据不返回;
  • 正则表达式[\\u4e00-\\u9fa5]{1,}表示匹配一个以上的汉字,这里用来匹配币种名称;
  • 在公式中,双引号有特殊用途,如果要输入一个普通的双引号,可以输入两个双引号,此时表示一个双引号;
  • $H$2,表示绝对引用,这样往下拖动公式时,引用的还是单元格H2;
  • 图中G列是辅助列,用来递增序号,以便获得要返回值的索引。

标签:

提交需求或反馈

Demand feedback