验证用户输入时,我使用正则表达式来检查每一行的开头(实际包含内容,跳过双空格),在任何其他字符之前总是有一组括号和内容.在摆弄了多种变体之后,这是我想出的最简单的版本,但失败了
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]*)+$/
如果任何行开头没有 (...)
模式,这将导致匹配失败。
关于javascript - 检查每行的第一个单词是否包含特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35998254/