UE C++基础 | 正则表达式
使用方式
- 头文件
#include "Internationalization/Regex.h"
- 案例:字幕信息
USTRUCT(BlueprintType)
struct FSubtitleData
{
GENERATED_USTRUCT_BODY()
public:
UPROPERTY(BlueprintReadOnly)
float StartTime;
UPROPERTY(BlueprintReadOnly)
float EndTime;
UPROPERTY(BlueprintReadOnly)
FString SpeakerName;
UPROPERTY(BlueprintReadOnly)
FString Content;
FSubtitleData()
: StartTime(0.0f)
, EndTime(0.0f)
, SpeakerName(TEXT(""))
, Content(TEXT(""))
{
}
FSubtitleData(float InStartTime, float InEndTime, FString InSpeakerName, FString InContent)
: StartTime(InStartTime)
, EndTime(InEndTime)
, SpeakerName(InSpeakerName)
, Content(InContent)
{
}
};
......
FString Src1 = TEXT("<时间开始=1.33 时间结束=2.23/><讲话者=小明/><讲话内容=早上好!/>");
FString Src2 = TEXT("<时间开始=2.86 时间结束=3.46/><讲话者=小红/><讲话内容=嗯,早!/>");
FString Src3 = TEXT("<时间开始=4.20 时间结束=5.20/><讲话者=小明/><讲话内容=今天好热!/>");
FString Src4 = TEXT("<时间开始=5.68 时间结束=6.68/><讲话者=小红/><讲话内容=对啊,38度呢!/>");
FString Src = FString::Prinf(TEXT("%s%s%s%s"), *Src1, *Src2, *Src3, *Src4);
FRegexPattern MatherPatter(TEXT("<时间开始=(.*?) 时间结束=(.*?)/><讲话者=(.*?)/><讲话内容=(.*?)/>"));
FRegexMatcher Matcher(MatherPatter, Src);
TArray<FSubtitleData> AllSubtitleData
while (Matcher.FindNext())
{
Matcher.GetCaptureGroup(0)
Matcher.GetCaptureGroup(1)
Matcher.GetCaptureGroup(2)
Matcher.GetCaptureGroup(3)
Matcher.GetCaptureGroup(4)
check(Matcher.GetCaptureGroup(1).IsNumeric());
check(Matcher.GetCaptureGroup(2).IsNumeric());
float StartTime = FCString::Atof(*Matcher.GetCaptureGroup(1));
float EndTime = FCString::Atof(*Matcher.GetCaptureGroup(2));
FString SpeakerName = Matcher.GetCaptureGroup(3);
FString Content = Matcher.GetCaptureGroup(4);
AllSubtitleData.Emplace(FSubtitleData(StartTime, EndTime, SpeakerName, Content));
}
......
AllSubtitleData[0].StartTime;
AllSubtitleData[0].EndTime;
AllSubtitleData[0].SpeakerName;
AllSubtitleData[0].Content;
AllSubtitleData[1].StartTime;
AllSubtitleData[1].EndTime;
AllSubtitleData[1].SpeakerName;
AllSubtitleData[1].Content;
AllSubtitleData[2].StartTime;
AllSubtitleData[2].EndTime;
AllSubtitleData[2].SpeakerName;
AllSubtitleData[2].Content;
AllSubtitleData[3].StartTime;
AllSubtitleData[3].EndTime;
AllSubtitleData[3].SpeakerName;
AllSubtitleData[3].Content;