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]
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top