0

having quite some trouble with the following regex.

String fktRegex ="public double " + a+ "2" + b + "(double value) {return value * (.*);}\n";

a and b are Strings that are inserted individually.

The regex works just fine until I want to identify also the number with it. That's the (.*) part... Any help`? Would be really glad! Thanks.

C.

2
  • 3
    Can you provide an example of the text you are searching in and a copy of the compiled regular expression please? Commented Jun 23, 2013 at 14:17
  • public double abc2xyz(double value) {return value * 100000;} However the datetype could be any numberbased datatype The text is a java sourcefile obviously. Don't know what u mean with compiled regex? Commented Jun 23, 2013 at 14:31

1 Answer 1

2

Judging by your example I think you need to escape few regex meta-characters like { } ( ) * so your regex should probably look more like

"public double " + a + "2" + b + "\\(double value\\) \\{return value \\* (.*);\\}\n";

Demo

// abc2xyz
String a = "abc";
String b = "xyz";

String fktRegex = "public double " + a + "2" + b + "\\(double value\\) \\{return value \\* (.*);\\}\n";

String data = "public double abc2xyz(double value) {return value * 100000;}\n";
Pattern p = Pattern.compile(fktRegex);
Matcher m = p.matcher(data);

if(m.find()){
    System.out.println(m.group(1));
}else{
    System.out.println("no match found");
}
Sign up to request clarification or add additional context in comments.

4 Comments

Cool, thanks!!! The only thing is now, that I the number back but I was planning to replace the whole function...?
@Chaoz77 I am not sure what you are trying to say (maybe its because my English is not too good yet). Try to describe it more or maybe even create another/separate question.
Sorry... Typo due to lacking browser... I was asking if there's a way to replace the whole function? The way u described it, i get back only the number. I don't want to extract the factor but the whole function and replace it with my regex.
@Chaoz77 if you want to get entire match then instead of group(1) use group(0) or just group(). Group 1 is the part between first parenthesis so part in regex so (.*) that is after return value \\* . If you would like want to lets say find entire return then you should probably use something like \\{(return value \\*.*;)\\} and now group 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.