[英]Javascript (node) regex doesn't seem to match start of string
im struggling with regular expressions in Javascript, they don't seem to start at the beginning of the string. 我正在用Java正则表达式苦苦挣扎,它们似乎不是从字符串的开头开始。 In a simple example bellow I want to get the file name and then everything after the first colon 在下面的简单示例中,我想获取文件名,然后获取第一个冒号之后的所有内容
//string
file.text:16: lots of random text here with goes on for ages
//regex
(.?)[:](.*)
// group 1 returns 't'
/^([^:]+):(.*)/.exec('file.text:16: lots of random text here with goes on for ages')
给....
["file.text:16: lots of random text here with goes on for ages", "file.text", "16: lots of random text here with goes on for ages"]
Try this regex: 试试这个正则表达式:
/^([^:]+)[:](.*)/
Explaination: 阐释:
^ #Start of string
( #Start of capturing class #1
[^:] #Any character other than :
+ #One or more of the previous character class
) #End of capturing class #1
[:] #One :
(.*) #Any number of characters other than newline
The ?
?
operator captures zero or one of the previous symbol only. 运算符仅捕获零或前一个符号之一。
You could also use string operations instead: 您也可以改用字符串操作:
str = "file.text:16:";
var n = str.indexOf(":");
var fileName = str.substr(0, n);
var everythingElse = str.substr(n);
The ? ? operator returns 0 or 1 matches. 运算符返回0或1个匹配项。 You want the * operator, and you should select everything that isn't a : in the first set 您需要*运算符,并且应该在第一组中选择所有非:的内容
([^:]*)[:](.*)
Non-regexy answer: 非正规答案:
var a = s.split(":");
Then join a[1] and remaining elements. 然后加入a [1]和其余元素。
Or just get the index of the first semicolon and create two strings using that. 或者只是获取第一个分号的索引,并使用它创建两个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.