Álvaro
Álvaro

Reputation: 2588

Regex for a matching regex

I want to check with JavaScript & Regex that a test only validates any kind of string between pipes |

So these will test true

`word|a phrase|word with number 1|word with symbol?`
`word|another word`

But any of these will say false

`|word`
`word|`
`word|another|`
`word`

I have tried this

const string = 'word|another word|'
// Trying to exclude pipe from beginning and end only
const expresion = /[^\|](.*?)(\|)(.*?)*[^$/|]/g
// But this test only gives false for the first pipe at the end not the second
console.log(expresion.test(string))

Upvotes: 1

Views: 55

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

The pattern [^\|](.*?)(\|)(.*?)*[^$/|] matches at least a single | but the . can match any character, and can also match another |

Note that this part [^$/|] mean any char except $ / |


You can start the match matching any character except a | or a newline.

Then repeat at least 1 or more times matching a | followed by again any character except a |

^[^|\r\n]+(?:\|[^|\r\n]+)+$

Explanation

  • ^ Start of string
  • [^|\r\n]+ Negated character class, match 1+ times any char except | or a newline
  • (?: Non capture group
    • \|[^|\r\n]+ Match | followed by 1+ times any char except a | or newline
  • )+ Close group and repeat 1+ times to match at least a single pipe
  • $ End of string

REgex demo

const pattern = /^[^|\r\n]+(?:\|[^|\r\n]+)+$/;
[
  "word|a phrase|word with number 1|word with symbol?",
  "word|another word",
  "|word",
  "word|",
  "word|another|",
  "word"
].forEach(s => console.log(`${pattern.test(s)} => ${s}`));

If there will be no newlines present, you can use:

^[^|]+(?:\|[^|]+)+$

Upvotes: 2

Related Questions