简体   繁体   English

如何使用正则表达式确定标头级别(JavaScript)

[英]How to Determine Header Level Using Regular Expressions (Javascript)

I am using Node.js to read a markdown file for my workplaces orders we take from customers. 我正在使用Node.js读取我从客户那里收到的工作场所订单的减价文件。 I am seperating the files into arrays of lines, and performing a check on each line to see what is it (h1, h3, task, etc) but am having lots of trouble getting my RegExps to work correctly. 我将文件分成几行,并在每行上执行检查以查看它是什么(h1,h3,任务等),但是让RegExps正常工作遇到很多麻烦。 Here is the code I have so far: 这是我到目前为止的代码:

var filesystem = require('fs');
let content;
let missingItems = [];

filesystem.readFile('orders.md', 'utf8', (err, res) => {
    let content = res;
    let lines = content.split('\n');
    lines.forEach(line => {
        if(line.match(/#{1}/)){
            console.log('Store Name: ', line);
        };
    });
});

This code, however returns all h1 AND h3 lines. 但是,此代码返回所有h1和h3行。 I saw using RegExp 101 online that the problem is that my RegExp is being matched 3 times for the h3 lines and one time for the h1 lines. 我看到在线使用RegExp 101,问题是我的RegExp被h3线匹配了3次,为h1线匹配了一次。

How can I write a regular expression that will not return true for both h1 and h3 lines? 如何编写对h1和h3行都不会返回true的正则表达式? I don't understand why this matches 3 times when I'm explicitly saying match {1} ( ONCE ) 我不明白为什么当我明确地说match {1}(ONCE)时会匹配3次

This is the testing area I've been testing my expressions with and some example text of what I am trying to test against: RegExp101 这是我一直在使用其测试表达式的测试区域,以及一些我要针对其进行测试的示例文本: RegExp101

You're asking if the line contains (at least) one # with that regex, which both lines do. 您正在询问该行是否包含(至少)一个带有该正则表达式的#,这两个行都包含。 you could use a negative lookahead: 您可以使用否定的前瞻:

^#(?!#)

^ means 'start of line', then the literal pound symbol, then the negative lookahead that takes the form of (?!pattern) , so we're looking ahead to NOT see another pound symbol. ^表示“行首”,然后是文字磅符号,然后是(?!pattern)形式的负前瞻,因此我们期待看到另一个磅符号。

Much simpler would be to test for the inital # and a following space \\s : 更简单的方法是测试初始#和以下空格\\s

^#\\s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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