Javascript regex 匹配(中间的随机字符串)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17985722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript regex match (random string in the middle)
提问by user2640648
I want to test if a string can match a pattern in javascript
我想测试一个字符串是否可以匹配 javascript 中的模式
problem is there is a random string in the middle pattern: "account/os/some_random_string/call_back"
问题是中间模式中有一个随机字符串:“account/os/ some_random_string/call_back”
so a string look like below will match
所以看起来像下面的字符串将匹配
var mystring = "account/os/1234567/call_back"
var mystring = "account/os/1234567/call_back"
thanks
谢谢
回答by Paul
You want a regex for starts with account/os/
and ends with /call_back
, here's one:
你想要一个以 开头account/os/
和结尾的正则表达式/call_back
,这是一个:
/^account\/os\/.*\/call_back$/
.*
will match any random string (including the empty string.). If you want a minimum length on the random string you change the *
:
.*
将匹配任何随机字符串(包括空字符串。)。如果您想要随机字符串的最小长度,请更改*
:
.* : 0 or more characters
.+ : 1 or more characters
.{n,} : n or more characters (replace n with an actual number)
回答by Silviu Burcea
Well, it depends. If you want every single character between account/os/ and /call_back, use this:
这要看情况。如果您想要 account/os/ 和 /call_back 之间的每个字符,请使用:
var randomStr = mystring.match(/account\/os\/(.*)\/call_back/)[1];
The match will return an array with 2 elements, the first one with the entire match, the 2nd one with the group (.*). If you are completely sure that you have at least one character there, replace * with +.
匹配将返回一个包含 2 个元素的数组,第一个包含整个匹配项,第二个包含组 (.*)。如果您完全确定那里至少有一个字符,请将 * 替换为 +。
If you know something more specific about the text you have to collect, here are some replacements for the .(dot is matching almost everything):
如果您对必须收集的文本有更具体的了解,这里有一些替代 .(点几乎匹配所有内容):
[A-z] for any of A, B, .. , Y, Z, a, b, .. , y, z
[0-9] for any digit
You can mix then and go fancy, like this:
你可以混合然后去幻想,像这样:
[A-Ea-e0-36-8]
So, your pattern may look like this one:
因此,您的模式可能如下所示:
/account\/os\/([A-Ea-e0-36-8]*)\/call_back/
Your example have a number there, so you are probably looking for:
您的示例在那里有一个数字,因此您可能正在寻找:
/account\/os\/([0-9]*)\/call_back/
or
或者
/account\/os\/(\d*)\/call_back/
.. it's the same thing.
.. 这是同一件事。
Hope that helps.
希望有帮助。
Edit: What JS answer doesn't have a jsfiddle? http://jsfiddle.net/U2Jhw/
编辑:什么 JS 答案没有 jsfiddle?http://jsfiddle.net/U2Jhw/