javascript - 检查每行的第一个单词是否包含特定字符

标签 javascript regex

验证用户输入时,我使用正则表达式来检查每一行的开头(实际包含内容,跳过双空格),在任何其他字符之前总是有一组括号和内容.在摆弄了多种变体之后,这是我想出的最简单的版本,但失败了

var regex = new RegExp('^\\([^)]+\\).*?$', 'm');

预期的结果是针对以下实例进行测试:

(test) whatever.\n(another test) again... whatever

(test) whatever.\n\n(another test) again... whatever

如果字符串中的任何一行以 ( 开头,括号内至少有一个字符,然后由 ) 结束,然后再包含任何数量的内容在括号之后,它应该失败; las,我上面的表达式将忽略任何检查第一行之后的任何行的尝试。如果我有一个格式错误的第二行,例如 (test) whatever\nthis) should return false,它仍然在 .test() 上返回 true。

一些有效的匹配项可能包括:

(test) pass

(test) pass\n(also) passes

(again) pass\n\n(also) pass\n(we) can do this all day

(There) can\n(be) any\n\n(amount) of \n(newlines) as\n\n\n\n(long) as each \n(line) that has \n(content) starts \n(with a) set of parenthesis.

(The) types\n\n(of) characters\n(don't) matter,\n(with) the only\n(exception) being the \n(strict enforcement) of the\n(open and close parenthesis) at the beginning of each line

一些应该在 .test() 上返回 false 的无效匹配包括:

Nope

Also Nope

(No closing parenthesis = Nope

Nope for the opposite of above)

(Yep so far) actually....\nNope

Big bowl of\n(Nope!)

) Take a guess?

() No good

最佳答案

要验证多行文本中以 (...) 开头的每一行,您可以使用此正则表达式:

/^(?:\(.+?\).*[\r\n]*)+$/

RegEx Demo

如果任何行开头没有 (...) 模式,这将导致匹配失败。

关于javascript - 检查每行的第一个单词是否包含特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35998254/

相关文章:

javascript - 在队列中预加载 mp3 文件以避免在播放队列中的下一个文件时出现任何延迟

javascript - 字符串化 JSON 的 Highcharts 选项

javascript - 如何添加淡入淡出

JavaScript 图表库 - Google Analytics 风格

c# - 骰子问题(满屋和直子识别)

regex - HTML5 模式匹配

javascript - 使用 js-cookie 和 JSON.parse 从 cookie 中设置和获取数组

javascript - 多维数组括号表示法的正则表达式

javascript - Nodejs 脚本取消某些代码行的注释或用文件中的内容替换注释

javascript - 用于年龄验证的正则表达式,仅使用 Javascript 接受 0-200 之间的年龄