有这样一个场景,软件检测到了一些文件,要从文件名中提取版号,实践生产中,文件名没有规律,根本无从知道,文件名中哪些数字代表的是版号,需要使用者编写javascript函数,自己从文件名中提取版号,实际文件名有可能是这样:20230405KJRBA01C.pdf,111.ps,2.ps,4106A01.pdf等等。
先建一个ClearScriptDemoApp,从nuget获取Microsoft.ClearScript.V8包,和Midcrosoft.ClearScript.V8.Native.win-64包,没有后面这个包,在windows下无法执行。
在项目中建一个viewmodels文件夹,建一个ParseFileNameViewModel.cs文件, 文件如下,
private string codeText ------>给用户写javascript代码
private string javascriptFunc ------->我们自己定义在javascript语言中使用的函数名getPageID(filename)
private string javascripEnd--------->给函数加末尾
完整代码:
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.ClearScript.V8;
namespace ClearScriptDemoApp.ViewModels
{
partial class ParseFileNameViewModel : ObservableObject
{
[ObservableProperty]
private string codeText;
[ObservableProperty]
private string javascriptFunc;
[ObservableProperty]
private string javascripEnd;
[ObservableProperty]
private string testFileName;
[ObservableProperty]
private string result;
public ParseFileNameViewModel()
{
JavascriptFunc = @"function getPageID(filename) { ";
javascripEnd = @" }";
TestFileName = "20230405KJRBA01C.pdf";
}
[RelayCommand]
async Task GetPageNum(string filename)
{
string pageNum = "";
using (var engine = new V8ScriptEngine())
{
try
{
engine.Execute(JavascriptFunc + CodeText + JavascripEnd);
pageNum = engine.Script.getPageID(filename).ToString();
}
catch (Exception ex)
{
pageNum = "语法错误,请检查代码。";
}
}
if(!pageNum.Contains("undefined"))
{
Result = await Task.FromResult(pageNum);
}
}
}
}
感觉clearscript非常好用,如此简单就满足了我的需求。
在项目中添加views文件夹,生成AnalysePage.xaml文件,内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewmodel="clr-namespace:ClearScriptDemoApp.ViewModels"
x:Class="ClearScriptDemoApp.Views.AnalysePage"
Title="AnalysePage">
<ContentPage.BindingContext>
<viewmodel:ParseFileNameViewModel/>
</ContentPage.BindingContext>
<Grid RowDefinitions="auto,*,0.1*,auto" Margin="5" RowSpacing="0">
<Label Text="{Binding JavascriptFunc}" BackgroundColor="LightGray" Padding="5"/>
<Editor Text="{Binding CodeText}" IsSpellCheckEnabled="False" IsTextPredictionEnabled="False" Grid.Row="1"/>
<Label Text="{Binding JavascripEnd}" Grid.Row="2" VerticalOptions="Start" HorizontalOptions="Start" BackgroundColor="LightGray" Padding="5"/>
<HorizontalStackLayout Grid.Row="3">
<Label Text="测试结果:" VerticalOptions="Center"/>
<Label Text="{Binding Result}" VerticalOptions="Center" MinimumWidthRequest="50"/>
<Label Text="文件名:" VerticalOptions="Center"/>
<Entry Placeholder="测试文件名" WidthRequest="300" VerticalOptions="Center" Text="{Binding TestFileName}"/>
<Button Text="测试" VerticalOptions="Center" Command="{Binding GetPageNumCommand}" CommandParameter="{Binding TestFileName}"/>
</HorizontalStackLayout>
</Grid>
</ContentPage>
App界面
在里面写上代码试试
完全正确,正是我们需要的效果。