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?

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

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.

0

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.

  • How can we calculate the CPU time even? Is there any specific metrics to use? – Arnold Jr. Jul 27 '17 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 Jul 27 '17 at 3:26
  • Does the internet connection plays any role in this calculation? – Arnold Jr. Jul 27 '17 at 3:29
  • No............. – Eric Jul 27 '17 at 3:34
  • Sounds good. I will make a note of this. Very helpful. – Arnold Jr. Jul 27 '17 at 3:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.