简体   繁体   English

一个正则表达式来匹配这个或恰好

[英]A regex to match this or exactly that

I am tryign to write a Markdown Parser ontop of the LDT JavaScript plugin, that allows a sort-of real-time parsing. 我试图在LDT JavaScript插件的顶部编写Markdown解析器,该插件可进行某种实时解析。 It has basic functions and one of them is a custom parser that uses Regex. 它具有基本功能,其中之一是使用Regex的自定义解析器。

While trying to implement a Markdown "parser", I got stuck on lists. 在尝试实现Markdown“解析器”时,我陷入了困境。 I want to match 我想搭配

- This string
* and that string

Or exactly 或者恰好

1. A string that starts with a number whic must be followed by a period.

So, when creating the parser, all the entries are concationated and separated with a pipe ( | ). 因此,在创建解析器时,所有条目都会被打包并用竖线( | )分隔。 The template is: new Regexp("^("+s+")$") . 模板是: new Regexp("^("+s+")$")

My current Regex to match unordered lists: 我当前的正则表达式以匹配无序列表:

 /[-\*]\s[^\n\r]*\n?/

...but this does also match in the center of a line. ...但是这也在直线的中心匹配。

What is the regex to match either - or * prefixed strings, or number prefixed strings, but which must have a period? -*前缀字符串或数字前缀字符串匹配的正则表达式是什么,但是必须有一个句点?

Avoiding the discussion if this is the right/wrong way to approach your desired task, you could use two group captures and beginning/end line boundaries . 如果这是处理所需任务的正确/错误方法,则可以避免讨论,可以使用两个组捕获和开始/结束行边界 The first group capture will allow you to test what type of list it is if there is a match. 第一个组捕获将允许您测试匹配的列表类型。

 var strings = [ '- This string', '* and that string', '1. A string that starts with a number which must be followed by a period.', 'Bad string', '-Bad string', '*Bad string', '2 Bad string.' ]; var matchRegExp = /^(\\d\\.|\\*|\\-)\\s(.+)$/; var res = strings.map(function (str) { return { str: str, match: str.match(matchRegExp) }; }); document.write('<pre>' + JSON.stringify(res, null, 4) + '</pre>'); 

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

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