简体   繁体   中英

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...

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]+)~/

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).

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

Is JavaScript/NodeJS capable of this?

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.

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. 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" .

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. The first slot has the full match, which in your case includes tildes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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