0

I need to find a match over the following text and I need to detect only one single under score by using REGEX:

Text: network_ip__c

Result: true

Text: Opportunity__c

Result: false

How can I accomplish this requirement in APEX?

3
  • can you elaborate a bit more? Do you want to find underscore only? Or anything that is between underscores?
    – Novarg
    Commented Feb 24, 2017 at 13:34
  • I need to find only one instance of underscore, for example, network_ip__c = true, Opportunity__c = false Commented Feb 24, 2017 at 14:08
  • 1
    There are a lot of sites that will help you with regex syntax, such as regex101.com
    – Folkert
    Commented Feb 24, 2017 at 14:20

2 Answers 2

3

Try this

_[^_c]

This searches for _ that is not followed by _c

Try it here: https://regex101.com/

enter image description here

You can test it this way:

String test1 = 'Opportunity__c';
String test2 = 'Opportunity_abc__c';
String regex = '_[^_c]';

System.debug(test1.split(regex).size() != 1); // false
System.debug(test2.split(regex).size() != 1); // true

This may be a bit wierd, but if string does not contain regex, it will not be split (1 element as result) and if it contains, it will have at least 2 elements.

1
  • what if you wanted to omit the c ? i.e get only the _ part
    – eran otzap
    Commented Mar 4, 2021 at 17:42
1

If you do not need regex you could simply do:

[string].replace('__','').contains('_');

If you are in Apex Not sure that regex would be required but that is up to you.

The regex (match all single non repeated occurrences of the character) would be: (?<!_)_(?!_) and will need to be adjusted for Apex.

5
  • How can we calculate the CPU time even? Is there any specific metrics to use?
    – SatyaV
    Commented Jul 27, 2017 at 3:24
  • Throw the code in a loop (size of your choosing, maybe 1000) with debug statements of the CPU time before and after the loop and output the difference. Do several times and take average
    – Eric
    Commented Jul 27, 2017 at 3:26
  • Does the internet connection plays any role in this calculation?
    – SatyaV
    Commented Jul 27, 2017 at 3:29
  • No.............
    – Eric
    Commented Jul 27, 2017 at 3:34
  • Sounds good. I will make a note of this. Very helpful.
    – SatyaV
    Commented Jul 27, 2017 at 3:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .