Java String用Array中的新模式替换为Regular表达式

时间:2015-12-09 12:25:38

标签: java arrays regex string replace

我遇到了一个我无法解决的问题

我有一个段落,其中包含一些关键字需要替换为存储在数组中的新值

示例:

  

段落:"我最喜欢的水果是[0],但我也喜欢[1]和[3]"

     

数组: fruits = [" Banana"," Orange"," Apple"," Grape" ]

我的期望是:My most favorite fruit is Banana, but I also like Orange and Grape

你能帮我找到解决方法吗?

我试图将我的句子转换为字符串数组,如下所示:

["My most favorite fruit is ","[0]",", but I also like ","[1]"," and ","[3]"]

之后,我将[0]替换为0,我得到了这个:

["My most favorite fruit is ","0",", but I also like ","1"," and ","3"]

我倾向于将上面数组中的013替换为fruits[0]fruits[1]fruits[3]的值然后转换该数组成为一个完整的字符串

但我认为这不是最好的解决方案,因为如果我得到这样的输入句子:"2[2]"那么我将收到输出 AppleApple ,而期望是 2Apple

5 个答案:

答案 0 :(得分:3)

Java string formatting有一个内置语法。一般格式为:

%[argument_index$][flags][width][.precision]conversion

所以你可以使用例如%1$s表示第一个格式参数,%2s表示第二个等。请注意,索引是从一开始的,而不是从零开始的。

e.g。

String[] fruits = {"Banana", "Orange", "Apple", "Grape"};
System.out.format(
    "My most favorite fruit is %1$s, but I also like %2$s and %4$s",
    fruits);

答案 1 :(得分:2)

使用String.replace

String sentence = "My most favorite fruit is [0], but I also like [1] and [3]";
String[] replacements = {"Banana", "Orange", "Apple", "Grape"};
for(int i = 0; i < replacements.length; i++)
    sentence = sentence.replace("[" + i + "]", replacements[i]);

答案 2 :(得分:1)

如果您能够更改paragraph的格式,那么您可以从此代码段开始。

String paragraph = "My most favorite fruit is %s, but I also like %s and %s";
String[] fruits = {"Banana", "Orange", "Apple", "Grape"};
System.out.printf(paragraph, fruits[0], fruits[1], fruits[2]);                 

输出

My most favorite fruit is Banana, but I also like Orange and Apple

编辑另一种无需维护水果位置参数的解决方案就可以了。

String paragraph = "My most favorite fruit is {0}, but I also like {1} and {3}";
Object[] fruits = {"Banana", "Orange", "Apple", "Grape"};
MessageFormat mf = new MessageFormat(paragraph);
System.out.println(mf.format(fruits));

输出

My most favorite fruit is Banana, but I also like Orange and Grape

答案 3 :(得分:0)

您可以使用以下代码(请参阅demo):

add_action( 'init', 'product_discount' );

function product_discount(){

//variable declerations.
global $woocommerce;
$product_id = 1; // product to add
$products= array('2', '3', '4'); //specific product(s) to be present in the cart
$coupon_code = 'abc'; // coupon code from wp

//get the cart contents.
$cart_items = $woocommerce->cart->get_cart();   
//check if the cart is not empty.
if(sizeof($cart_items) > 0){    
    //loop through the cart items looking for the specific products.
    foreach ($cart_items as $key => $item){     
        //check if the cart items match to any of those in the array and check if the desired product is in the cart.
        if(in_array($item['product_id'], $products) && $item['product_id'] != $product_id){ 
                //add course.
                $woocommerce->cart->add_to_cart($product_id);
                //discount course.
                $woocommerce->cart->add_discount(sanitize_text_field($coupon_code));
            }else{
                break; //to prevent the product from being added again for the next loop.
            }
    }           
}   
}

使用ArrayList<String> fruits_arr = new ArrayList<String>(); // Just initializing the array fruits_arr.add("Banana"); fruits_arr.add("Orange"); fruits_arr.add("Apple"); fruits_arr.add("Grape"); String[] fruits = fruits_arr.toArray(new String[0]); String s = "My most favorite fruit is [0], but I also like [1] and [3]"; StringBuffer result = new StringBuffer(); Matcher m = Pattern.compile("\\[(\\d+)\\]").matcher(s); // Initializing Matcher while (m.find()) { // Iterate over matches int num = Integer.parseInt(m.group(1)); // If there is a match, Group 1 has digits String replacement = ""; if (num < fruits.length) { // If the number is lower than fruit element count replacement =fruits[num]; // Get the array element } else { replacement = m.group(); // Else, use the whole match (e.g. [9]) } m.appendReplacement(result, replacement); // Append this replacement } m.appendTail(result); System.out.println(result.toString()); ,您可以将任何子字符串与\[(\d+)] + [ + digits匹配,并将数字序列捕获到第1组。

答案 4 :(得分:0)

您可以使用以下内容:

    String str = "My most favorite fruit is [0], but I also like [1] and [3]";
    String[] fruits = { "Banana", "Orange", "Apple", "Grape" };

    for (int i = 0; i < fruits.length; i++)
    {
        str = str.replaceAll("\\[" + i + "\\]", fruits[i]);
    }