try this
String type = str.replaceAll(".*\\s(.)\\s*=.*", "$1");
سؤال
I am writing a method that accepts a string which is only java attribute/field declaration and returns only the attribute name. e.g.:
private double d = 1000;
private boolean b;
private final int f = 100;
private char c = 'c';
so if the parameter is one of the above the method should return only d, b, f or c. How is algorithms should be implemented. I have tried to use regex to strip the word after the types but it became very complicated. Can anyone give me some clues, thanks
المحلول
try this
String type = str.replaceAll(".*\\s(.)\\s*=.*", "$1");
نصائح أخرى
You can take the string before the equal sign without regex:
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(true){
String theString = sc.nextLine();
String left = theString.split("=")[0].trim(); // Split into variable part and value part
int lastSpace = left.lastIndexOf(" "); // there must be a space before a variable declaration, take the index
String variableName = left.substring(lastSpace+1); // take the variable name
System.out.println(variableName);
}
}
If you're implementing this on Python, it's much easier:
the_string = 'private double d = 1000;'
print the_string.split('=',1)[0].strip().rsplit(' ',1)[1]