字符串操作 [英] String manipulation

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

问题描述

给定一个输入字符串,我想从这个得到输出指定格式为:文件名;路径

Given an input string, I would like to get the output from this in the specified format: filename;path.

有关输入字符串 / VOB / TEST /.@@/主/ ch_vobsweb / 1 / VOBSWeb /主/ ch_vobsweb / 4 / VobsWebUI /主/ ch_vobsweb / 2 / VaultWeb /主/ ch_vobsweb /2/func.js

我希望这种输出字符串:
func.js; VOBSWeb / VosWebUI / VaultWeb / func.js

I expect this output string: func.js;VOBSWeb/VosWebUI/VaultWeb/func.js

的文件名被列出在整个字符串的末尾,和其路径应该使用剥离每个数值后面的字符(如 / 1 / VOBSWeb / 然后 / 4 / VobsWebUI 然后 / 2 / vaultWeb

The filename is listed at the end of the whole string, and its path is supposed to be stripped using the characters after each numeric value (eg. /1/VOBSWeb/ and then /4/VobsWebUI and then /2/vaultWeb)

推荐答案

如果路径数是任意的,则你需要一个两步走的方法:

If the number of paths is arbitrary, then you need a two-step approach:

首页后,删除所有无趣的东西从字符串。

First, remove all the "uninteresting stuff" from the string.

搜索。*?/ \d + /([^ /] + /?)并更换所有与 $ 1

在C#中: resultString = Regex.Replace(subjectString,@ * / \d + /([^ /] + /?),$ 1);

在JavaScript的:<? code>结果= subject.replace(/.* \ / \d + \ /([^ \ /] + \ /)/克,$ 1?);

In JavaScript: result = subject.replace(/.*?\/\d+\/([^\/]+\/?)/g, "$1");

这将改变你的字符串转换成 VOBSWeb / VobsWebUI / VaultWeb / func.js

This will transform your string into VOBSWeb/VobsWebUI/VaultWeb/func.js.

,复制文件名字符串的前面。

Second, copy the filename to the front of the string.

搜索([^ /] +)$ 替换$ 2(* /); $ 1 $ 2

C#: resultString = Regex.Replace(subjectString,(* /)([^ /] +)$ ,$ 2,$ 1 $ 2);

JavaScript的:结果= subject.replace(/(.* \ /)([^ \ /] +)$ /克,$ 2,$ 1 $ 2);

JavaScript: result = subject.replace(/(.*\/)([^\/]+)$/g, "$2;$1$2");

这将改变前面操作的结果为 func.js; VOBSWeb / VobsWebUI / VaultWeb / func.js

This will transform the result of the previous operation into func.js;VOBSWeb/VobsWebUI/VaultWeb/func.js

如果路径的数量是恒定的,那么你可以做它在一个单一的正则表达式:

If the number of paths is constant, then you can do it in a single regex:

搜索 ^。*?/ \d + /([^ /] + /)。*?/ \d + /([^ /] + /)。*?/ \d + /([^ /] + /)。 ?* / \d + /([^ /] +)

和替换与 $ 4; $ 1 $ 2 $ 3 。$ 4'/ code>

and replace with $4;$1$2$3$4.

C#:<?code> resultString = Regex.Replace(subjectString,@^ * / \d + /([^/]+/).*?/ \d + /([^ /] + /)。*?/ \d + /([^ /] + /)。*?/ \d + /( [^ /] +),$ 4; $ 1 $ 2 $ 3 $ 4);

JavaScript的:的结果= subject.replace(/^.*?\ / \d + \ /([^ \ /] + \ /).*?\ / \d + \ /([^ \ /] + \ /).*?\ / \d + \ /([^ \ /] + \ /).*?\ / \d + \ /([^ \ /] +)/克,$ 4; $ 1 $ 2 $ 3 $ 4);

JavaScript: result = subject.replace(/^.*?\/\d+\/([^\/]+\/).*?\/\d+\/([^\/]+\/).*?\/\d+\/([^\/]+\/).*?\/\d+\/([^\/]+)/g, "$4;$1$2$3$4");

如果字符串不匹配该正则表达式将是低效的;这可能是与固化分组得到改善,但JavaScript不支持。

This regex will be inefficient if the string fails to match; this could be improved with atomic grouping, but JavaScript doesn't support that.

这篇关于字符串操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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