Sergey Shustikov
Sergey Shustikov

Reputation: 15821

Java regex replace String in file

I try to replace String via regex.

Target String :

if (ValidationUtil.checkNullable(groupDataObject) || !groupDataObject.isNotificationEnable() ||

Regex

.*(ValidationUtil\DcheckNullable)([a-zA-Z0-9]*).*

Replace pattern

$2 == null

Wishful result :

if (groupDataObject == null || !groupDataObject.isNotificationEnable() ||

And it's not worked. It produce result == null.What i'm doing wrong?

Upvotes: 1

Views: 120

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626826

You can use the following regex:

(ValidationUtil\DcheckNullable)\(([a-zA-Z0-9]*)\)
                               ^^              ^^

I removed .* and added \( and \).

See the regex demo

If you need to also match parentheses and dots, just include them in the character class:

(ValidationUtil\DcheckNullable)\(([a-zA-Z0-9().]+)\)
                                            ^^^

See this regex demo

Note that instead of \D, you can use the dot, just remember it should be escaped with double backslash in a Java string literal: String pat = "(ValidationUtil\\.checkNullable)\\(([a-zA-Z0-9().]+)\\)"

Upvotes: 2

Mitesh Pathak
Mitesh Pathak

Reputation: 1306

$2 is null, because there is no match for next group since the following character is (

.*(ValidationUtil\.checkNullable)\(([a-zA-Z0-9]*)\).*

Try the above pattern, it has \( which then skips ( and finds the group 2 match. Also if you just want to extract groupDataObject, add a trailing \)

Upvotes: 0

Related Questions