简体   繁体   English

正则表达式替换第一行中的某些字符

[英]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 X s only on the first line, and replacing that with nothing would result in: 仅在第一行匹配所有大写的X ,然后不进行任何替换将导致:

Hello dude
How areX yXou?
FxIXne?

This matches only the first X: 这仅匹配第一个X:

/X/m

This matches all Xs: 这与所有X匹配:

/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. 我已经花了数小时来寻找解决方案,但是我在想,也许我根本不了解正则表达式逻辑。

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: 以此处的JavaScript为例,您的代码可能如下所示:

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 ;) 问题的分解是学习的一种很好的技巧;)

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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM