简体   繁体   中英

Select everything after dash “-” RegEx || JavaScript

So I am working with Regex inside JavaScript to get data matched from a plain text file with various list items starting with a dash "- ".

At first I used the following RegEx:

/(?<=- |\d\. ).*/g

But it turns out Positive Lookbacks aren't allowed to be used anymore in browsers so they currently only work with Chrome but no other browsers.

I then tried to get around this without using a lookback by using:

(\-\ |\d\.\ ).+

But this also selects the actual dash and first space which is also something I do not want as I need everything behind the first dash and space.

The info I have is formatted like:

- List item 1
- List item 2
- List item 3
- List item 4

And I require the output as "List item #" for every single row in the text file. Can someone perhaps guide me in the right direction to solve this or an alternative to the JavaScript .match() function?

Thanks in advance.

You can capture the substring after the - or number like this:

(?:- |\d\. )(.*)

Group 1 will contain the text you want.

 var string = `- List item 1 - List item 2 - List item 3 - List item 4` var regex = /(?:- |\\d\\. )(.*)/g var match = null while (match = regex.exec(string)) { console.log(match[1]); // match[1] is the string in group 1 } 

Alternatively,

console.log(string.replace(regex, "$1"))

which will replace the whole match with group 1. This method is suitable if you want the output as one single string instead of an array of lists.

Put it in a non-capturing group: (?:\\-\\ |\\d\\.\\ )(.+) .

Results look like this: https://regex101.com/r/OwZl8g/1

If they are the first thing to match on the line, you could match from the start of the string 0+ times a space (or space and tabs in a character class), use and alternation to match either a dash or a digit and a dot. Then use a capturing group to capture what follows:

^ *(?:-|\\d+\\.) (.*)$

 const strings = [ '- List item 1', ' 1. List item 2', '1. List item 3' ]; let pattern = /^ *(?:-|\\d+\\.) (.*)$/; strings.forEach(s => { console.log(s.match(pattern)[1]); }); 

maybe you could give us an example of your input text.

const regexp = /(?:- )(\w)/g;
const input = '- a, some words - b';
const result = input.match(regexp); // result: ['- a','- b']

I highly recommend you use https://regexper.com to visualize your RegEx.

Hope these could help you.

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