How to compute a regex match against an object's parameter by name?

B

BogusException

Consider that you want to do a regex match on the contents of an
attribute of that object. Say, for example, the contents of:

SomeObjectInstance.x

All is well unless you don't know ahead of time that "x" is the
attribute that the user will search against. Suppose that the object
can have any attribute name, and even all those possibilities aren't
known at compile time. The user can/will select this attribute, as well
as the regex pattern.

So the trick is how to apply the match against "x" in this case with
only "x" as a string passed to the method?

// this doesn't work!
public boolean isRegexMatch(String p, String m, SomeObject o, String
attribute){
Pattern pat = Pattern.compile(p);
Matcher mat = pat.matcher(o."attribute"); <--- doesn't work, obviously
return (mat.find());
}

The above would be nice, but as expected-it doesn't work.

So the question is, how to make the method functional without knowing
what it will be passed for "attribute"?

TIA!

BogusException
 
S

Stefan Ram

BogusException said:
o."attribute"

public class Main
{ public final java.lang.String attribute = "alpha";
public static void main( java.lang.String[] args )
throws
java.lang.NoSuchFieldException,
java.lang.IllegalAccessException
{ final Main main = new Main();
System.out.println
( main.getClass().getField( "attribute" ).get( main )); }}

alpha
 
J

Jean-Francois Briere

public boolean isRegexMatch(String pattern, Object obj, String attName)
throws Exception {
String attValue =
(String)obj.getClass().getField(attName).get(obj);
Matcher matcher = Pattern.compile(pattern).matcher(attValue);

return matcher.find();
}
 
B

BogusException

Jean-Francois and Stefan,

Thank you very much for your posts! I'm continually surprised at how
much this language can do, and how little it can't! I appreciate your
contribution to my work, and this group, very much.

:)

BogusException
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Regex to match a numerical IP range 7
regex problem 9
Regex: match double OR single quote 4
Java regex can't match lengthy match? 0
complex regex 1
complex regex 1
Why is regex so slow? 21
Regex challenge 15

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top