balaji
balaji

Reputation: 794

Regular Expressions for restricting _ at the end

I have a regular expression ^[\\p{L}\\d._]*\\p{L}+[\\p{L}\\d._]*$ and this works fine for

  1. ABC123de (alphanumeric - irrespective of the case)
  2. ABCDEfgh (only alphabets - irrespective of the case)
  3. Abc_.123 (only special characters allowed are _ and .)

However, it is accepting inputs like

  1. balaji_,jacob_ (having _ at the end)
  2. 2balaji,2jacob (starting with a numeric)

Can we modify the above regular expression to restrict the above two test cases?

Upvotes: 0

Views: 211

Answers (2)

Richard
Richard

Reputation: 109025

The first peice of this:

^[\p{L}\d._]*\p{L}+[\p{L}\d._]*$

has * which allows zero or more, first to fix issue #2 change that to a +: one or more:

^[\p{L}\d._]+\p{L}+[\p{L}\d._]*$.

To prevent underscores at the end need another clause which doesn't include _:

^[\p{L}\d._]+\p{L}+[\p{L}\d._]*[\p{L}\d.]?$.

But this would still allow a _ alone (from the first part matching alone). If you don't want a sole underscore just remove from that first clause:

^[\p{L}\d.]+\p{L}+[\p{L}\d._]*[\p{L}\d.]?$.

If the ability to start with an underscore is needed I think we need more information about allowable cases for single and double character strings.

Upvotes: 0

Keppil
Keppil

Reputation: 46219

Sure, add the appropriate restrictions to the beginning and end like this:

^\p{L}[\p{L}\d._]*\p{L}+[\p{L}\d._]*[\p{L}\d.]$

Upvotes: 1

Related Questions