从带有字符索引的字符串中获取子字符串 [英] Get substring from string with the index of the characters

查看:45
本文介绍了从带有字符索引的字符串中获取子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 .txt 文件中获取信息:

I'm trying to get information from a .txt file:

function1(par1, par2)
function2(par1)
function3(par1, par2, par3)

例如,我想将第一行function1"作为字符串,par1"和par2"作为字符串.

I would like to get for example for the first line "function1" as a string, "par1" and "par2" as strings.

我现在可以从字符串中提取模式,但我想知道是否可以使用字符索引获取子字符串.

I now it is possible to extract a pattern from a string, but I would like to know if it was possible to get a substring using the index of its caracters.

例如在 Python 中:

For example as in Python :

$function = $row[0:8]

会给我function1"

would get me "function1"

谢谢,

SLP

推荐答案

解析函数调用的编程文本,如示例输入所示

To parse programming text of a function call, as shown in the sample input

my $string = 'function1(par1, par2)';

my ($func_name, @params) = split /\s*\(\s*|\s*,\s*|\s*\)/, $string;

其中 split 内置使用正则表达式作为分隔符模式,我们告诉它通过 (, ) 拆分字符串(我还包括右括号,以便最后一个元素不会被卡住它).正则表达式模式也有可能散布的空间.

where split builtin uses a regex for the separator pattern, and we tell it to break up the string by either ( or , or ) (I also include the closing parenthesis so that the last element wouldn't be stuck with it). The regex pattern also has possible spaces sprinkled around.

如果您的 .txt 文件确实有像您显示的那样的行,那么您可以简单地将上述内容应用到每一行.如果每行都有更多内容,那么您需要先对其进行预处理(或使用不同的方法);如果线条比显示的多,请显示真实的输入.

If your .txt file has literally lines like what you show then you can simply apply the above to each line. If there is more on each line though then you'd need to preprocess that first (or use a different approach); please show the realistic input if lines have more than what is shown.

这篇关于从带有字符索引的字符串中获取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆