简体   繁体   English

正则表达式与字符集中的$不匹配

[英]Regex does not match $ in character set

I'm currently fighting a weird javascript regex problem. 我目前正在解决一个奇怪的javascript正则表达式问题。 I'm trying to match all characters between / or the end of input. 我正在尝试匹配/或输入结尾之间的所有字符。 For example this string 例如这个字符串

admin/item/get

should be matched as: 应该匹配为:

[ 'admin', 'item', 'get' ]

I don't really care if / is part of the match or not, so this result would work for me too: 我并不在乎/是否是比赛的一部分,所以这个结果也适用于我:

[ 'admin/', 'item/', 'get' ]

To match the input string s I'm using the regex 为了匹配输入字符串s我使用正则表达式

s.match(/.+?[\/$]/g)

which results in 导致

[ 'admin/', 'item/' ]

To my understanding the end of input $ is not matched in this character set. 据我了解,此字符集中输入$的末尾不匹配。

When I try to match only the end of input using the regex s.match(/.+?$/g) I'm getting the expected result [ 'admin/item/get' ] . 当我尝试使用正则表达式s.match(/.+?$/g)仅匹配输入结尾时,我得到了预期的结果[ 'admin/item/get' ] But placing the $ in a character set s.match(/.+?$/g) the match call returns null . 但是将$放在字符集s.match(/.+?$/g) ,match调用返回null

Any help appreciated... 任何帮助表示赞赏...

Btw: I'm using node.js 0.8.20 顺便说一句:我正在使用node.js 0.8.20

Because $ is treated as a character when placed inside a character set. 因为$放在字符集中时会被视为字符。 This should do it though, it uses an alternation inside a non-memory capturing group and thus restores the meaning of $ to be the end-of-subject: 不过,应该这样做,因为它在非内存捕获组中使用了交替方式,因此将$的含义恢复为主题的结尾:

s.match(/.+?(?:\/|$)/g)

["admin/", "bla/", "bla"]

As mentioned in the comments: 如评论中所述:

s.split('/')

["admin", "bla", "bla"]

$ within character class [] has no special meaning and is treated as literal character 字符类[] $没有特殊含义,被视为文字字符

It should be 它应该是

.*?(?=\/|$)

You can instead do this..you dont have to check for / or $ 您可以改为执行此操作。您不必检查/$

[^/]*

You can attain the result using regex or split method for string object. 您可以使用正则表达式或字符串对象的split方法获得结果。

var s = "admin/item/get";

Using split method of string object. 使用字符串对象的拆分方法。

Split the string by "/" . "/"分割字符串。

s.split("/");

["admin", "item", "get"]

Using regex pattern. 使用正则表达式模式。

Match the string with regular expression /[^\\/]+/g , which matches all characters with occurence of one or more times except "/" character. 用正则表达式/[^\\/]+/g匹配字符串,该表达式匹配所有出现一次或多次( "/"字符除外)的字符。

s.match(/[^\/]+/g)

["admin", "item", "get"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM