正则表达式按顺序查找单词但在其他单词之间

时间:2015-12-04 06:55:43

标签: java android regex

我在为特定场景实现正则表达式时遇到问题。

让我们说输入是“棕色的狗”,可以从“快速的棕色狐狸跳过懒狗”中搜索出来。它应该在以下条件下返回true:

  1. - 不区分大小写
  2. - 必须按顺序排列(第一个单词是'the',第二个单词是'brown',第三个单词是'dog')。
  3. 这意味着像“狗棕色”,“狐狸棕色”,“快速狐狸棕色”等输入将返回虚假但“狗”,“快速棕色”,“跳过”返回真实。我希望我提供了足够的样本。

    到目前为止,我的正则表达式"(?i)(?:\\S+\\s)?\\S*"+targetString+"\\S*(?:\\s\\S+)?"仅适用于完全字符串,但不适用于其他字词。

1 个答案:

答案 0 :(得分:1)

 /// <summary>
    /// Converter for simple math operations. It should be bound to a source path, which has a number for its value.
    /// the parameter should be a string with a format of "N|xxxxx" (without quotes), where N is a number, the '|'
    /// sign is a separator and the second parameter (xxxxx) is a string defining the operation. Valid values are
    /// add, subtract, multiply and divide. Below example shows how a button's width is set to one third of the
    /// parent's canvas width:
    /// <Canvas x:Name="mainCanvas" Height="220" Width="260">
    ///     <Button x:Name="button1" 
    ///                Content="Button" 
    ///                Height="30" 
    ///                Canvas.Left="0" Canvas.Top="79" 
    ///                Width="{Binding ElementName=mainCanvas, Path=Width, 
    ///                                Converter={local:ScreenRatioConverter}, 
    ///                                ConverterParameter='3|divide'}"/>
    /// </Canvas>
    /// </summary>
    [ValueConversion(typeof(string), typeof(string))]
    public class ScreenRatioConverter : MarkupExtension, IValueConverter
    {
        private static ScreenRatioConverter _instance;

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string parameterString = parameter as string;
            string[] parameters = parameterString.Split(new char[] { '|' });
            double par1 = System.Convert.ToDouble(value);
            double par2 = System.Convert.ToDouble(parameters[0], CultureInfo.InvariantCulture);
            string operation = (string)parameters[1];
            double result = 20; //Default value to return if anything goes wrong.
            if (operation.Equals("add"))
            { result = par1 + par2; }
            else if (operation.Equals("subtract"))
            { result = par1 - par2; }
            else if (operation.Equals("multiply"))
            { result = par1 * par2; }
            else if (operation.Equals("divide"))
            { result = par1 / par2; }

            return result;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        //Needs to be overridden because of inheritance from MarkupExtension.
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return _instance ?? (_instance = new ScreenRatioConverter());
        }

    }

}

查看this