TransWikia.com

I am trying to create a regex for a list of accepted symbols and character string

Stack Overflow Asked on November 15, 2021

I am building a test function that should only accept the following:

-
*
+
.
,
$
9
Z
V
B
CR – only once not with DB
DB – only once not with CR

I have gotten the first few to work like so: new RegExp(/^([-*+.,$9ZVB]|CR|DB)*$/gm), but I annot get the regex to only allow the CR or DB to appear only once either at beginning or end of the string. Any suggestions?

Test at https://regex101.com/r/1qT86R/2

2 Answers

I'm guessing you are using javascript.

You can use the regex:

^(?:(?:CR|DB)[-*+.,$9ZVB]+|[-*+.,$9ZVB]+(?:CR|DB))$

Demo & explanation

var test = [
    '$---,---,--9.99BCR',
    '$---,---,--9.99BDB',
    'CR$---,---,--9.99B',
    'DB$---,---,--9.99B',
    'CR$---,---,--9.99BCR',
    'CR$---,---,--9.99BDB',
];
console.log(test.map(function (a) {
  return a+' : '+/^(?:(?:CR|DB)[-*+.,$9ZVB]+|[-*+.,$9ZVB]+(?:CR|DB))$/.test(a);
}));

Answered by Toto on November 15, 2021

Try this expression:

^(CR|DB)[-*+.,$9ZVB]+$|^[-*+.,$9ZVB]+(CR|DB)$

or

^((CR|DB)[-*+.,$9ZVB]+|[-*+.,$9ZVB]+(CR|DB))$

You can test it here: https://regexr.com/58tf1

Answered by Ilya Lysenko on November 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP