我有以下示例資料。最終目標是即時翻譯(翻譯成另一種語言,比如西班牙語)方括號外的資料。
下面的代碼適用于大多數情況,但是當括號 [] 在字串內時,由于明顯的原因,它對最后一個資料失敗。
所以我想知道如何撰寫一個只會抓取括號外內容的運算式。與我現在正在做的完全相反。請記住,有些訊息可能根本沒有任何方括號。您可以假設左括號總是有右括號。
namespace RegExDemo
{
class Program
{
static void Main(string[] args)
{
string[] data = new string[]
{
"[00:05:00] Insert buckle tongue [0/1 = 5.81mA]",
"Remove buckle tongue [1/1 = 5.81mA]",
"Move track forward",
"Move track forward [MinCrt: 1.0, 0.1A, MaxCrt: 5.0] [MinPos: 450mm, 420, 520mm]",
"Waiting before taking reading [500ms]",
"Waiting [500ms] before taking reading"
};
var regEx = new Regex(@"\[(.*?)\]");
foreach (var instruction in data)
{
var instructionsOnly = regEx.Replace(instruction, string.Empty).Trim();
var newInstruction = "'This is now Spanish: " instructionsOnly "'";
var newFinalValue = instruction.Replace(instructionsOnly, newInstruction);
Console.WriteLine(newFinalValue);
}
Console.WriteLine("All done");
Console.ReadLine();
}
}
}

uj5u.com熱心網友回復:
不完全符合您的要求,但我建議您這樣做:
using System.Text.RegularExpressions;
namespace RegExDemo
{
class Program
{
static void Main(string[] args)
{
string[] data = new string[]
{
"[00:05:00] Insert buckle tongue [0/1 = 5.81mA]",
"Remove buckle tongue [1/1 = 5.81mA]",
"Move track forward",
"Move track forward [MinCrt: 1.0, 0.1A, MaxCrt: 5.0] [MinPos: 450mm, 420, 520mm]",
"Waiting before taking reading [500ms]",
"Waiting [500ms] before taking reading"
};
var regEx = new Regex(@"\[.*?\]"); // lose the parentheses
var placeholder = "SOMETHINGTHETRANSLATIONSERVICECANBETRUSTEDNOTTOTRYTOTRANSLATE";
foreach (var instruction in data)
{
var matches = regEx.Matches(instruction);
string tmp = instruction;
for (int i = 0; i < matches.Count; i )
{
tmp = tmp.Replace(matches[i].Value, $"{placeholder}{i:0000}");
}
var newInstruction = "'This is now Spanish: " tmp "'";
for (int i = 0; i < matches.Count; i )
{
newInstruction = newInstruction.Replace($"{placeholder}{i:0000}", matches[i].Value);
}
var newFinalValue = newInstruction;
Console.WriteLine(newFinalValue);
}
Console.WriteLine("All done");
Console.ReadLine();
}
}
}
我在機器翻譯服務方面有一些經驗,通常他們會單獨留下全部大寫的單詞混搭。但是您可以嘗試一系列符號或任何似乎適用于您的特定服務的東西。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/385027.html
