#Check if value is RegExp

60 messages · Page 1 of 1 (latest)

rocky elk
#

In my code, I have type checks.

In this situation, I'm trying to check if something is a RegExp.

value instanceof RegExp

The RegExp check returns false on /^some:thing.*$/ which would be from dev.latvian.mods.rhino.regexp.NativeRegExp

How would I check if a value is a RegExp? I think this approach only catches RexExp s made with new RegExp() (not tested) but it def. doesn't work with /^$/ regexes.

I looked in Rhino's code and didn't find anything to check is something is a RexExp.

Was thinking about doing

let regex = /^tieredshulkers:.*shulker_box((?!upgrade).)*$/;
let str = regex.toString();
let isRegExp = false;

if (str.startsWith('/') && str.lastIndexOf('/') > 0) {
    console.log('The string representation of regex looks like a RegExp');
    isRegExp = true;
} else {
    console.log('The string representation of regex does not look like a RegExp');
}

but this is not the best approach ofc.

balmy pythonBOT
#

Once your ticket has been resolved, please close it with </ticket close:1054771505520717835> command!

rocky elk
#
console.log(/^word.*$/ instanceof RegExp);
console.log(typeof /^word.*$/);

gives

[07:06:14] [INFO] tags/items.js#28: true
[07:06:14] [INFO] tags/items.js#29: function
#

it returns true, hmmm

#

Ah wait this is outside any event

#

Hmmm in event gives same

sharp cairn
#

can you do something like

const NativeRegExp = /_/.constructor;
function isRegExp (x) {
    return x instanceof RegExp || x instanceof NativeRegExp;
}
rocky elk
#
console.log(/^word.*$/ instanceof RegExp);
console.log(typeof /^word.*$/);
console.log(/^word.*$/);

returns

[07:12:06] [INFO] tags/items.js#41: true
[07:12:06] [INFO] tags/items.js#42: function
[07:12:06] [INFO] tags/items.js#43: /^word.*$/ [dev.latvian.mods.rhino.regexp.NativeRegExp]
#

What does .constructor do?

sharp cairn
#

it gets the constructor of a value

#

so for example (2).constructor === Number

rocky elk
#

What would the underscore do/be?

sharp cairn
#

just a convention that signifies the contents aren't important, you can put something else if you want

rocky elk
#

I also tried loading in the class and then doing some things with it, but wasn't successful :p

sharp cairn
rocky elk
#
/**
 * Checks if a value is of instance RegExp. Expects exactly one argument.
 *
 * @param {*} value - The value to check.
 *
 * @returns {boolean} True if the value is of instance RegExp and exactly one argument is provided, false otherwise.
 */
const isRegExp = checkArguments((value) => value instanceof RegExp || value instanceof /_/.constructor, 1);
#

I will try this now

sharp cairn
#

fwiw the reason i used a constant was because i wasn't sure if doing value instanceof /_/.constructor would initialize a new regexp every time it was executed

#

using a constant is probably premature optimization though

#

also fwiw if the docs are accurate it's better practice to throw an error if the wrong number of args are supplied

rocky elk
#

Im working on the checkArguments function and currently I log a warn instead of throwing an error. Wasn't sure yet what to do

#

Btw what does fwiw mean 😄

sharp cairn
#

for what it's worth

rocky elk
#
function logWarning(expected, received, action, name) {
    console.warn(`[WARN] Expected ${expected}, but received ${received}. Aborting ${action} for ${name}...`);
}
        if (!numArgs.includes(arguments.length)) {
            logWarning(
                `arguments length to be one of ${numArgs.join(', ')}`,
                arguments.length,
                'function call',
                func.name
            );
            return;
        }

would you throw an error instead?

rocky elk
# sharp cairn can you do something like ```js const NativeRegExp = /_/.constructor; function i...
[07:39:58] [WARN] tags/tag_utils.js#97: [WARN] [minecraft:item] Invalid 'elementsToAdd'. It should be a non-empty string, a regular expression or an array containing only non-empty strings or regular expressions. Skipping adding to #forge:chests.
[07:39:58] [INFO] tags/tag_utils.js#100: elementsToAdd:
[07:39:58] [INFO] tags/tag_utils.js#100: /^ironchest:.*chest$/ [dev.latvian.mods.rhino.regexp.NativeRegExp]
#

Should I check it with typeof or instanceof?

sharp cairn
sharp cairn
rocky elk
#

Here is the actual check:

    /* Checks if 'elementsToAdd' is a non-empty string, a regular expression, or an array of non-empty strings or regular expressions. */
    if (
        !(
            isStringAndNotEmpty(elementsToAdd) ||
            isRegExp(elementsToAdd) ||
            (isArrayAndNotEmpty(elementsToAdd) &&
                elementsToAdd.every((element) => isStringAndNotEmpty(element) || isRegExp(element)))
        )
    ) {
        console.warn(
            `[WARN] [${tagType}] Invalid 'elementsToAdd'. It should be a non-empty string, a regular expression or an array containing only non-empty strings or regular expressions. Skipping adding to #${tagId}.`
        );
        console.log('elementsToAdd:', elementsToAdd);
        return;
    }
#

And the helper function do the obvious thing of returning true or false depending whether the value is exactly what the function name says

#

Can't I do

value instanceof dev.latvian.mods.rhino.regexp.NativeRegExp

or how can I do a similar check to this?

sharp cairn
#

yeah i just don't know what the path for NativeRegExp is

rocky elk
#

Isn't this the path? dev.latvian.mods.rhino.regexp.NativeRegExp

sharp cairn
#

not sure, try it

rocky elk
#

Is there a way to get the info at the end, then turn it into a string and then in the RegExp check see if the string matches 'dev.latvian.mods.rhino.regexp.NativeRegExp'

#

[07:39:58] [INFO] tags/tag_utils.js#100: /^ironchest:.*chest$/ -> [dev.latvian.mods.rhino.regexp.NativeRegExp] <-

sharp cairn
# rocky elk

wrt this you could try import dev.latvian.mods.rhino.regexp.NativeRegExp and then try value instanceof NativeRegExp

rocky elk
#

Or is there a way, if I load in the class, to see when a value, when it does a function out of the NativeRegExp class, for example getClassName, doesn't error?

Can't explain it well Im sorry

sharp cairn
#

that's sensible

rocky elk
#

And then assume that when it doesn't error, it is a NativeRegExp?

sharp cairn
#

which methods of NativeRegExp are you using?

rocky elk
#

or actually do the function which return the string "RegExp"

rocky elk
#

But I can't load in the class, then do value.getClassName() (which is from Rhino) if value isn't of that class

sharp cairn
#

i gtg for now, sorry

rocky elk
rocky elk
#

Hmmmm

    let x = /^word.*$/;
    console.log(x.constructor);

RegExp [dev.latvian.mods.rhino.regexp.NativeRegExpCtor]

fickle sky
#

@rocky elk can you show us why do you need to differentiate those regexes or whatever?

#

I'm curious if you actually need that

rocky elk
#

I have a function that adds elements to a given tag, and the elements can be strings, RegExp s or an array with strings and/or RegExp s, so I just want to check whether the provided value is one of these

fickle sky
#

iirc it supports all that, just throw at the array and you don't need to do nothing

rocky elk
#

It's more for learning purposes, I'm overcomplicating my kjs scripts to learn, even when kjs would handle false arguments by its own 🙂

fickle sky
#

I see, but be careful because Rhino may give you headache

rocky elk
#

Weeeeeeell... XD

#

I think I start to feel what you're saying xd

fickle sky
#

what happens when you console.printObject(/_/)

rocky elk
# fickle sky what happens when you console.printObject(/_/)
[09:02:35] [INFO] tags/items.js#52: === dev.latvian.mods.rhino.regexp.NativeRegExp ===
[09:02:35] [INFO] tags/items.js#52: = toString() =
[09:02:35] [INFO] tags/items.js#52: > /_/
[09:02:35] [INFO] tags/items.js#52: = hashCode() =
[09:02:35] [INFO] tags/items.js#52: > cb3495b
[09:02:35] [INFO] tags/items.js#52: 
[09:02:35] [INFO] tags/items.js#52: === dev.latvian.mods.rhino.regexp.NativeRegExp ===
[09:02:35] [INFO] tags/items.js#52: = Parent class =
[09:02:35] [INFO] tags/items.js#52: > dev.latvian.mods.rhino.IdScriptableObject
[09:02:35] [INFO] tags/items.js#52: = Variables and Functions =
[09:02:35] [INFO] tags/items.js#52: > val className: String
[09:02:35] [INFO] tags/items.js#52: > val typeOf: MemberType
[09:02:35] [INFO] tags/items.js#52: > function call(Context, Scriptable, Scriptable, Object;): Object
[09:02:35] [INFO] tags/items.js#52: > function construct(Context, Scriptable, Object;): Scriptable
[09:02:35] [INFO] tags/items.js#52: > function execIdCall(IdFunctionObject, Context, Scriptable, Scriptable, Object;): Object
[09:02:35] [INFO] tags/items.js#52: > function init(Context, Scriptable, boolean): void
[09:02:35] [INFO] tags/items.js#52: > function toString(): String