【问题标题】:Function to match text in {word1|word2} format以 {word1|word2} 格式匹配文本的函数
【发布时间】:2011-03-18 09:04:45
【问题描述】:

正确地说我有一个字符串,例如{i|we|my friends} are {just|about} to go {walmart|asda|best buy} 我希望能够随机选择{} 中的任何单词,由| 分隔这是我到目前为止所拥有的,它只适用于一个{} 我需要它来处理具有多个{} 的句子。

Function UnspinWork(ByVal SpunWords As String) As String
    Dim upperBound As Integer
    Dim Random As New Random()
    Dim ChosenSpunString As String
    SpunWords = Replace(SpunWords, "{" & "}", "")
    upperBound = Split(SpunWords, "|").Count
    ChosenSpunString = Split(SpunWords, "|")(Random.Next(0, upperBound))
    Return ChosenSpunString
End Function

谢谢

【问题讨论】:

  • 好吧,如果我用多个 {word1|word2} 一些文本 {word1|word2} 向它发送句子,它只会拆分第一个 {}

标签: .net regex vb.net .net-4.0 random


【解决方案1】:

使用正则表达式查找所有 {} 部分。然后使用 Regex.Replace 方法,使用 MatchEvaluator 能够指定什么是替换。 在这个 MatchEvaluator 中,您可以添加随机选择的逻辑。

在c#中(对不起,不习惯VB)你可以这样做:

class SpunWords
{
    static Random rnd = new Random();
    static void Main()
    {
        var source = "{i|we|my friends} are {just|about} to go {walmart|asda|best buy}";

        var pattern = @"\{(?<values>[^\}]*)\}";

        var result = Regex.Replace(
            source,
            pattern,
            (m) => Rand(m.Groups["values"].Value)
            );

        Console.WriteLine(result);

        Console.ReadLine();
    }
    private static string Rand(string value)
    {
        var parts = value.Split('|');
        return parts[rnd.Next(parts.Length)];
    }
}

【讨论】:

    【解决方案2】:

    我只是将 steve b's 从 c# 转换为 vb.net(幸运的是我知道 c#)

    Class SpunWords
        Shared rnd As New Random()
        Private Shared Sub Main()
            Dim source = "{i|we|my friends} are {just|about} to go {walmart|asda|best buy}"
    
            Dim pattern = "\{(?<values>[^\}]*)\}"
    
            Dim result = Regex.Replace(source, pattern, Function(m) Rand(m.Groups("values").Value))
    
            Console.WriteLine(result)
    
            Console.ReadLine()
        End Sub
        Private Shared Function Rand(value As String) As String
            Dim parts = value.Split("|"C)
            Return parts(rnd.[Next](parts.Length))
        End Function
    End Class
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      相关资源
      最近更新 更多