Home > Mobile >  Regex for multiline text area
Regex for multiline text area

Time:10-25

I am trying to validate text area. Format should be us following:

Text description: ${VARIABLE_NAME} \n
Text description: ${VARIABLE_NAME} 

Rules:

  1. Text description can contain a-zA-Z0-9 spaces and "_"
  2. Text description need to be followed ":"
  3. ":" can be followed with no or one space
  4. after ": " string need to start with "${"
  5. "VARIABLE_NAME" can contain only A-Z and "_"
  6. "VARIABLE_NAME" and line need to finish with "}"

Text can have multiple lines, every line need to follow all 6 rules.

For now i have this regex const regex = new RegExp('[\\w ]:\\$\\{[A-Z] }$', 'gs'); Just not sure how to handle multiple lines.

CodePudding user response:

The requirements can be matched as follows:

  1. [\w ] 2. → : 3. →  ? 4. → \$\{ 5. → [A-Z_] 6. → }

Put into a (?: non capturing group (?:\n|$)) for one or more lines.

^(?:[\w ] : ?\$\{[A-Z_] }(?:\n|$)) $

See this demo at regex101 or a JS demo at tio.run (use \r?\n for CRLF support)

CodePudding user response:

You can use

/^[\w ] :[^\S\r\n]?\${[A-Z_] }(?:\r?\n[\w ] :[^\S\r\n]?\${[A-Z_] })*$/

See the regex demo. Details:

  • ^ - start of string
  • [\w ] - one or more alphanumeric/underscore/space chars
  • : - a colon
  • [^\S\r\n]? - an optional horizontal whitespace
  • \${ - a ${ string
  • [A-Z_] - one or more uppercase ASCII letters or underscores
  • } - a } char
  • (?:\r?\n[\w ] :[^\S\r\n]?\${[A-Z_] })* - zero or more repetitions of the CRLF or LF line ending sequence followed with the above explained pattern
  • $ - end of string.

CodePudding user response:

You may be looking for the m multiline flag:

const text = "Foo: ${A_1}\nBar Baz: ${B_12}";

const rx = /^[a-zA-Z0-9_ ] : ?\$\{[A-Z0-9_] \}$/gm; 
                                             // ^^ global   multiline flags

console.table(text.match(rx));
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script><script>console.config({maximize:true,timeStamps:false})</script><style>.as-console-wrapper{display:block;}</style>

  • Related