Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex match string with only one occurrence of __ characters

Tags:

regex

I am struggling with some regex to match the strings I need. This is what I have so far, but it's matching more than I want:

(\w*__c|\w*__r|[a-zA-Z0-9]*)\.\w*__c|\w*__c

Here are some examples of what I want to match/not match:

FFX_GLAAssetDisposalID__c                                   => TRUE
FAM__Asset_Sub_Group__r.PNL_On_Asset_Disposal_GL_Account__c => TRUE
Product2.SalesRevenueAccount__c                             => TRUE
ffbext__codabecashmatchingreport                            => FALSE
Product2.c2g__CODASalesRevenueAccount__c                    => FALSE

Where items are separated by a . the significant thing is the number of __ in the part after the . where there can be no more than one set of __. I've also experimented with negative lookaheads to no avail.

like image 892
Phil Hawthorn Avatar asked Sep 13 '25 10:09

Phil Hawthorn


1 Answers

You should bear in mind that \w matches letters, digits and underscore. To be able to control the number of underscores, one needs to use [^\W_] character class, that is, \w with underscore subtracted.

You may use

\b(?:\w+\.)?[^\W_]+(?:_[^\W_]+)*__c\b

See the regex demo

Details

  • \b - a word boundary
  • (?:\w+\.)? - an optional sequence of 1+ letters/digits/underscores and then a .
  • [^\W_]+ - one or more letters or digits
  • (?:_[^\W_]+)* - zero or more sequences of _ and then one or more letters/digits
  • __c - a __c string
  • \b - a word boundary
like image 113
Wiktor Stribiżew Avatar answered Sep 16 '25 08:09

Wiktor Stribiżew