Scott
Scott

Reputation: 6736

Check that first word of each line contains specific characters

When validating user input, I'm using a regular expression to check that at the beginning of each line (that actually contains content, double spaces are skipped), there is always a set of parenthesis with content within before any other characters. After fiddling around with multiple variations, here's the most simplistic version I came up with that is failing

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

The intended result is to test true against instances such as:

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

or

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

If any line in the string does begin with a (, have at least one character within the parenthesis, and is then closed by ) before having any amount of content after the parenthesis, it should fail; alas, my expression above will ignore any attempt at checking any line past the first. If I have a malformed second line such as (test) whatever\nthis) should return false, it still returns true on a .test().

Some valid matches might include:

(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

Some invalid matches that should return false on a .test() include:

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

Upvotes: 2

Views: 89

Answers (2)

Curious Sam
Curious Sam

Reputation: 1289

Did you mean

var regex = /^(?:(?:^|\r*\n)(?:[\t ]*|\s*\([\t ]*(?:[^\(\)\s][\t ]*)+\)[^\r\n]*))*$/;

Regular expression visualization

Test it live on Debuggex

Upvotes: 0

anubhava
anubhava

Reputation: 785266

To validate every line starts with (...) in a multiline text you can use this regex:

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

RegEx Demo

This will fail the match if any line start doesn't have (...) pattern.

Upvotes: 1

Related Questions