UE C++基础 | 正则表达式

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()) // 会执行4次。因为按顺序匹配到4次
{
	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;	// 1.33
AllSubtitleData[0].EndTime;		// 2.23
AllSubtitleData[0].SpeakerName;	// 小明
AllSubtitleData[0].Content;		// 早上好!

AllSubtitleData[1].StartTime;	// 2.86
AllSubtitleData[1].EndTime;		// 3.46
AllSubtitleData[1].SpeakerName;	// 小红
AllSubtitleData[1].Content;		// 嗯,早!

AllSubtitleData[2].StartTime;	// 4.20
AllSubtitleData[2].EndTime;		// 5.20
AllSubtitleData[2].SpeakerName;	// 小明
AllSubtitleData[2].Content;		// 今天好热!

AllSubtitleData[3].StartTime;	// 5.68
AllSubtitleData[3].EndTime;		// 6.68
AllSubtitleData[3].SpeakerName;	// 小红
AllSubtitleData[3].Content;		// 对啊,38度呢!
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Flame老唐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值