[英]Regex to find text between second and third slashes
I would like to capture the text that occurs after the second slash and before the third slash in a string.我想捕获字符串中第二个斜杠之后和第三个斜杠之前出现的文本。 Example:
例子:
/ipaddress/databasename/ /IP地址/数据库名/
I need to capture only the database name.我只需要捕获数据库名称。 The database name might have letters, numbers, and underscores.
数据库名称可能包含字母、数字和下划线。 Thanks.
谢谢。
How you access it depends on your language, but you'll basically just want a capture group for whatever falls between your second and third "/".您如何访问它取决于您的语言,但您基本上只需要一个捕获组来处理您的第二个和第三个“/”之间的任何内容。 Assuming your string is always in the same form as your example, this will be:
假设您的字符串始终与您的示例格式相同,这将是:
/.*/(.*)/
If multiple slashes can exist, but a slash can never exist in the database name, you'd want:如果可以存在多个斜杠,但数据库名称中永远不能存在斜杠,则您需要:
/.*/(.*?)/
/.*?/(.*?)/
The regex would be:正则表达式将是:
/[^/]*/([^/]*)/
so in Perl, the regex capture statement would be something like:所以在 Perl 中,正则表达式捕获语句将类似于:
($database) = $text =~ m!/[^/]*/([^/]*)/!;
Normally the /
character is used to delimit regexes but since they're used as part of the match, another character can be used.通常
/
字符用于分隔正则表达式,但由于它们被用作匹配的一部分,因此可以使用另一个字符。 Alternatively, the /
character can be escaped:或者,可以转义
/
字符:
($database) = $text =~ /\/[^\/]*\/([^\/]*)\//;
You can even more shorten the pattern by going this way:通过这种方式,您甚至可以进一步缩短模式:
[^/]+/(\w+)
you can use explode
function with PHP
or split
with other languages to so such operation.您可以使用
PHP
的explode
函数或与其他语言split
来进行此类操作。
anyways, here is regex pattern:无论如何,这是正则表达式模式:
/[\/]*[^\/]+[\/]([^\/]+)/
I know you specifically asked for regex, but you don't really need regex for this.我知道您专门要求使用正则表达式,但您实际上并不需要正则表达式。 You simply need to split the string by delimiters (in this case a backslash), then choose the part you need (in this case, the 3rd field - the first field is empty).
您只需用分隔符(在本例中为反斜杠)拆分字符串,然后选择您需要的部分(在本例中,第三个字段 - 第一个字段为空)。
cut<\/code> example:
cut<\/code>示例:
cut -d '\/' -f 3 <<< "$string"<\/code><\/pre><\/li>
awk<\/code> example:
awk<\/code>示例:
awk -F '\/' {print $3} <<< "$string"<\/code><\/pre><\/li>
perl<\/code> expression, using
split<\/code> function:
perl<\/code>表达式,使用
split<\/code>函数:
![](/img/trans.png)
(split '\/', $string)[2]<\/code><\/pre><\/li><\/ul> etc.等等。
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.