Arun Christopher
Arun Christopher

Reputation: 402

Regex to find first occurence of a character in lines matching a character

I am trying to do find and replace in my eclipse workspace on all properties files. The condition is that I have to find the lines which has the character '<' and then get the first matching "=" character on those matched lines.

For example

app.searchform.height.label=Height <b>(in cm)</b>

I want to find the char = in the above line and replace it with like =<has_html> so I get the below output

app.searchform.height.label=<has_html>Height <b>(in cm)</b>

Upvotes: 2

Views: 88

Answers (2)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You may use this regex,

(?=.*<)=

And replace it with,

=<has_html>

Explanation: Positive look ahead ensures the replacement only occurs if it finds < character in the string. And then just matches with = and replaces it with =< has_html>.

Demo, https://regex101.com/r/yLt9j4/1

Edit1: Here is how you can do it in java codes for replacing only first occurrence of =,

public static void main(String[] args) {
    String s = "app.searchform.height.label=Height <b>(in =cm)</b>";

    System.out.println("Before: " + s);
    s = s.replaceFirst("(?=.*<)=", "=<has_html>");
    System.out.println("After: " + s);
}

This gives following output,

Before: app.searchform.height.label=Height <b>(in =cm)</b>
After: app.searchform.height.label=<has_html>Height <b>(in =cm)</b>

Upvotes: 3

doom87er
doom87er

Reputation: 468

You can try this one:
^(.*?)=(?=.*<)

With this as the replacement string:
$1=<has_html>

Working Example

Explanation:
In order to limit matches to 1 per line I start the match at the beging of the line with ^
Then uses a lazy quantifier to expand out words, stuffing everything into a capture group to paste back in later with (.*?)
then terminate the expansion o a = character and use a lookahead (?=.*<) to check for the < character

Upvotes: 1

Related Questions