James
James

Reputation: 33

Regex to replace certain characters on first line

I'm thinking that this is something very simple, but I can't find an answer anywhere online. I've found results on how to match the whole first line in a multiline string, but not how to find all occurrences of a certain character ONLY on the first line.

So for instance:

HelloX dXudXe
How areX yXou?
FxIXne?

Matching all capital Xs only on the first line, and replacing that with nothing would result in:

Hello dude
How areX yXou?
FxIXne?

This matches only the first X:

/X/m

This matches all Xs:

/X/g

So I'm guessing the answer is the regex version of one of these statements:

"Replace all X characters until you find a newline"
"Replace all X characters in the first line"

This sounds like such a simple task, is it? And if so, how can it be done? I've spent hours looking for a solution, but I'm thinking that maybe I don't get the regex logic at all.

Upvotes: 3

Views: 1596

Answers (2)

Barmar
Barmar

Reputation: 781300

Split the string into multiple lines, do the replacement on the first line, then rejoin them.

var lines = input.split('\n');
lines[0] = lines[0].replace(/X/g, '');
input = lines.join('\n');

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Without knowing the exact language you are using, it's difficult to give an example, but the theory is simple:

If you have a complex task, break it down.

In this case, you want to do something to the first line only. So, proceed in two steps:

  1. Identify the first line
  2. Perform an operation on it.

Using JavaScript as an example here, your code might look like:

var input =
    "HelloX dXudXe" + "\n" +
    "How areX yXou?" + "\n" +
    "FxIXne?";

var result = input.replace(/^.*/,function(m) {
    return m.replace(/X/g,'');
});

See how first I grab the first line, then I operate on it? This breaking down of problems is a great skill to learn ;)

Upvotes: 4

Related Questions