Notepad ++:如何正确分组,以便替换工作


0

我得到了替换“\ n \ 1 = \ 2”。我的工作是创建一个搜索模式,以便替换成功。

我的数据是这样的:

There are Spanish translations for some names like Mary (Maria), John (Juan), Michael (Miguel) and Joseph (Jose). 

我的目标是让它看起来像这样:

There are Spanish translations for some names like 
Mary = Maria
John = Juan
Michael = Miguel
Joseph = Jose.

我到目前为止的搜索是“是。|,。| \和。+(^ [a-z] \ S)+(。* \ S)”。即使搜索的第一部分有效,也不能在替换时进行正确的分组。我不知道从搜索中改变什么或者应该如何改变以使其工作。

Answers:


2
  • 按Ctrl + H
  • 找什么: (\w+)\h+\((\w+)\)\h*(?:,|and)?\h*(\.)?
  • 用。。。来代替: \n$1 = $2$3
  • 检查包裹
  • 检查正则表达式
  • 全部替换

说明:

(\w+)       # group 1, 1 or more word characters, English name
\h+         # 1 or more horizontal spaces
\(          # openning parenthesis
(\w+)       # group 2, 1 or more word characters, the Spanish name
\)          # closing parenthesis
\h*         # 0 or more horizontal spaces
(?:         # non capture group
    ,       # a comma
  |         # OR
    and     # literally and
)?          # end group, optional
\h*         # 0 or mor horizontal spaces
(\.)?       # group 3, a dot, optional

替换:

\n          # linefeed, you can use \r\n for windows linebreak
$1          # content of group 1
 =          # space, equal sign, space
$2          # content of group 2
$3          # content of group 3

给出示例的结果:

There are Spanish translations for some names like 
Mary = Maria
John = Juan
Michael = Miguel
Joseph = Jose. 

屏幕截图:

enter image description here


0

我不是特别熟悉 具有Notepad ++的搜索和替换功能, 但是Unix的 sed 非常相似。

我相信你无法获得 精确 你想要的结果 随着 精确 你展示的替换字符串, 因为你想要西班牙名字之前的空格(  Maria Juan等), 但输入文本中没有这样的空格。 您需要在替换字符串中添加至少一个空格。

-r 选项告诉 sed 使用“扩展正则表达式”。 我们并不一定需要这个选项,但是

  • sed (默认情况下)使用 () 匹配括号, 和 \(…\) 同时捕捉一个群体
  • sed -r 使用 \(\) 与字面括号相匹配, 和 (…) 捕捉一个团体。

你似乎期待能够使用 (…) 抓住一个团体, 所以我会这样做 -r

你可以做到这一点是一个替代 sed

sed -r 's/\s([A-Za-z]*)\s\(([A-Za-z]*)\)(,| and)*/\n\1 = \2/g'

这可以分解为

sed -r 's/   \s   ([A-Za-z]*)   \s   \(   ([A-Za-z]*)   \)   (,| and)?   /   \n\1 = \2   /g'
  • s/ - 开始替代命令。
  • \s - 空间。 在 sed,你可以使用实际的空格字符; 我怀疑Notepad ++也是如此。 在 sed 你也可以用 [[:space:]]。 当然,空间只与空间相匹配, 但 \s[[:space:]] 匹配空格或制表符。
  • ([A-Za-z]*) - 任意数量字母的捕获组 (大写或小写),以匹配名称的英文版本。 在 sed 你也可以用 [[:alpha:]] (要么 [[:upper:]] 要么 [[:lower:]], 如预期的)。
  • \s - 另一个空间。
  • \( - 左括号 (西班牙语版本之前的那个)。
  • ([A-Za-z]*) - 与上述相同 - 任意数量字母的捕获组 (大写或小写),以匹配西班牙语版本的名称。
  • \) - 字面右括号 (西班牙语版本之后的那个)。
  • (,| and)? - 匹配的组 , 要么  and,零或一次。 这匹配之间的东西 西班牙语版本后的右括​​号, 和下一个英文版名称。 我们需要能够处理该组的零次出现 因为我们需要匹配 Joseph (Jose), 即使没有逗号或“ and “在它之后。
    请注意,我们可以使用 \sand 代替  and; 我相信  and 更具可读性。 另请注意,我们可以使用 * (零或更多,没有限制) 代替 ?
  • / - 搜索字符串的结尾;更换字符串的开头。
  • \n\1 = \2 - 你的替换字符串 (换行,第一个捕获组,  = ,和第二个捕获组)。 如前所述,我在之前和之后添加了空格 =
  • /g - 结束命令。 该 g 代表“全局”并指定替换 应该尽可能多地执行(默认值是每行一次)。

所以Notepad ++命令可能非常相似。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.