[英]Javascript Regex match text between tildes
I feel like an idiot because I've spent a long time trying to find a regex that will work. 我觉得自己是个白痴,因为我花了很长时间试图找到一个可以使用的正则表达式。
String: ~05276~^~0500~^~Turkey...
字串:
~05276~^~0500~^~Turkey...
The ... means that there can be an unlimited number of characters after. ...表示后面可以有无限多个字符。 What I want is the first tilde delimited number without the tildes.
我要的是没有波浪号的第一个波浪号定界数字。 I'm trying to pull some data from a text file, and I think that I can figure the rest out if I can understand how to do this.
我正在尝试从文本文件中提取一些数据,如果可以理解该方法,我想可以弄清楚其余的数据。
Here's my regex as it stands: /^~([\\d]+)~/
这是我的正则表达式:
/^~([\\d]+)~/
This is what I'm getting: 这就是我得到的:
[ '~05276~',
'05276',
index: 0,
input: '~05276~^~0500~^~Turkey...' ]
When I use the g operator ( /^~([\\d]+)~/g
), I'm only getting the ~05276~
, and what I want is the 05726
(no tildes). 当我使用g运算符(
/^~([\\d]+)~/g
)时,我只能得到~05276~
,而我想要的是05726
(无波浪号)。
I've found a few different posts and resources, but I can't seem to figure out why this isn't working as I expect. 我发现了一些不同的帖子和资源,但是我似乎无法弄清为什么它没有按我期望的那样工作。 Here's what I found:
这是我发现的:
Javascript regex - how to get text between curly brackets Javascript正则表达式-如何在大括号之间获取文本
Is JavaScript/NodeJS capable of this? JavaScript / NodeJS能够做到这一点吗?
Edit: 编辑:
Here's my code: 这是我的代码:
lineReader.eachLine(file, function (line) {
var entry = {};
entry.id = line.match(/^~([\d]+)~/);
console.log(entry);
});
lineReader is working properly and returns a line like in my example string above. lineReader正常工作,并返回类似于上面示例字符串中的一行。
You'r regex is (almost) fine, but you're probably not using it right. 您的正则表达式(几乎)很好,但是您可能没有正确使用它。 Here's what I'd do if I wanted an array of the numbers:
如果我想要一个数字数组,这就是我要做的事情:
var array = [];
yourString.replace(/~(\d+)~/g, function(_, n) { array.push(n); });
What you really don't need is that leading "^" anchor. 您真正不需要的是领先的“ ^”锚点。
You only need the regex /\\d+/
in order to match the first number after tilde in your example. 您只需要正则表达式
/\\d+/
即可匹配示例中波浪号后的第一个数字。 Your method would then be: 您的方法将是:
lineReader.eachLine(file, function (line) {
var entry = {};
entry.id = line.match(/\d+/);
console.log(entry);
});
With input "~05276~^~0500~^~Turkey"
you will get the result "05276"
. 输入
"~05276~^~0500~^~Turkey"
,将得到结果"05276"
。
Regarding the array answer you get, it's because you have parentheses, ie a capture group. 关于获得的数组答案,是因为您有括号,即捕获组。 If it's a match the group captured, starting at the leftmost parenthesis --
(\\d+)
in your case -- will reside in the second slot of the result array. 如果是匹配的组,则从最左括号开始
(\\d+)
在您的情况下为(\\d+)
将驻留在结果数组的第二个插槽中。 The first slot has the full match, which in your case includes tildes. 第一个插槽具有完全匹配项,在您的情况下,其中包括波浪号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.