在轨道上的红宝石中更换字符串

时间:2015-10-06 07:38:31

标签: ruby

我有一个像

这样的文字
details = "1. Command id = 22 Time = 2:30 <br> 2. Command id = 23 Time = 3:30"

现在我需要将其转换为

"1. http://localhost:3000/command_id=22/home Time = 2:30 <br> 2. http://localhost:3000/command_id=23/home Time = 3:30"

我使用了正则表达式和gsub,但它不会这样做,因为gsub将替换相同的字符串。然后有一些使用sedawk的技术。

要提取所有ID,如22,23,我使用

details.scan(/Command id = [0-9]+/).join(",").scan(/[0-9]+/)

有任何想法如何进行上述转换?

6 个答案:

答案 0 :(得分:2)

Why dont you just use

details.gsub(' Command id =', '')

It generates expected result

"1. 22 Time = 2:30 <br> 2. 23 Time = 3:30"

EDIT:

details.gsub('Command id = ', 'http://localhost:8000/')

It will generate

 "1. http://localhost:8000/22 Time = 2:30 <br> 2. http://localhost:8000/23 Time = 3:30"

答案 1 :(得分:2)

简单的正则表达式

function cmp($a,$b){
         if ($a["id_user"] == $b["id_user"]) {
            return 0;
        }
        return ($a < $b) ? -1 : 1;
    }

    $unique_and_merged_array = array();
    $unique_and_merged_array[0]['id_user'] = 1;
    $unique_and_merged_array[0]['tokenId'] = 123;
    $unique_and_merged_array[1]['id_user'] = 2;
    $unique_and_merged_array[1]['tokenId'] = 456;
    $unique_and_merged_array[2]['id_user'] = 5;
    $unique_and_merged_array[2]['tokenId'] = 789;
    $unique_and_merged_array[3]['id_user'] = 2;
    $unique_and_merged_array[3]['tokenId'] = 752;
    $unique_and_merged_array[4]['id_user'] = 3;
    $unique_and_merged_array[4]['tokenId'] = 789;
    usort($unique_and_merged_array, "cmp");

答案 2 :(得分:2)

string.gsub('Command id =', '')

答案 3 :(得分:1)

只需用空字符串替换Command id =

string.gsub(/\s*\bCommand\s+id\s+=/, "")

答案 4 :(得分:0)

试试这个纯正则表达式并获得预期的输出

sed 's/[^"]\+\([^ ]\+\)[^=]\+=\([^\.]\+.\)[^=]\+.\(.*\)/\1\2\3/' FileName

sed 's/Command id =\|details = //g' FileName

输出

"1. 22 Time = 2:30 <br> 2. 23 Time = 3:30"

答案 5 :(得分:0)

1. http://localhost:3000/command_id=22/home Time = 2:30 <br> 2. http://localhost:3000/command_id=23/home Time = 3:30

输出:if ([UIAlertController class]) { // use UIAlertController UIAlertController *alert= [UIAlertController alertControllerWithTitle:@"Enter Folder Name" message:@"Keep it short and sweet" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){ //Do Some action here UITextField *textField = alert.textFields[0]; NSLog(@"text was %@", textField.text); }]; UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { NSLog(@"cancel btn"); [alert dismissViewControllerAnimated:YES completion:nil]; }]; [alert addAction:ok]; [alert addAction:cancel]; [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) { textField.placeholder = @"folder name"; textField.keyboardType = UIKeyboardTypeDefault; }]; [self presentViewController:alert animated:YES completion:nil]; }

当然可以进一步自动化