【问题标题】:Robotframework:How to replace parts of regex matches stringsRobotframework:如何替换部分正则表达式匹配字符串
【发布时间】:2016-05-10 11:06:08
【问题描述】:

我在以下环境中使用机器人框架。

  • Python 2.7.6
  • 机器人框架 2.8.7
  • Ubuntu 14.04.3 LTS

如果匹配 "[0-9]*" 模式,我想从字符串中删除 " 字符。
我的代码如下,但这不能工作未知参数。

*** Settings ***
Library    Collections
Library    json
Library    String

*** Variables ***
${TARGET_STRING}   {"host": "['192.168.1.2', '192.168.1.3']", "part": "['ZZZ1', 'ZZZ2']", "name": "XXXX", "kara": null, "type": "123", "id": "YYYY", "flg": false,"type2": "4567","type3": "4"}


*** Test Cases ***
My Test Case
    ${resp}    My Keyword    ${TARGET_STRING}

*** Keywords ***
My Keyword
    [Arguments]    ${string}
    ${resp}    Replace String Using Regexp    ${string}    "[0-9][0-9][0-9]"   123
    ${resp}    Replace String Using Regexp    ${resp}    "[0-9][0-9][0-9][0-9]"   4567
    ${resp}    Replace String Using Regexp    ${resp}    "[0-9]"   4
    Log To Console    ${resp}

输出

 {"host": "['192.168.1.2', '192.168.1.3']", "part": "['ZZZ1', 'ZZZ2']", "name": "XXXX", "kara": null, "type": 123, "id": "YYYY", "flg": false,"type2": 4567,"type3": 4}

(在这种情况下,我想改变
“类型”:“123”到“类型”:123,
“type2”:“4567”到“type2”:4567,
"type3": "4" 改成 "type3": 4 不改其他)

如何概括它?

【问题讨论】:

    标签: regex robotframework


    【解决方案1】:

    你可以使用这个正则表达式:

    "[^"]+"\s*:\s*)"([0-9]+)"
    

    用于此的 Python 可能类似于:

    p = re.compile(ur'("[^"]+"\s*:\s*)"([0-9]+)"', re.IGNORECASE | re.MULTILINE)
    

    替换字符串将是:$1$2。这将有效地重新组合这两个部分,而数字周围没有引号。

    【讨论】:

      猜你喜欢
      • 2011-05-28
      • 2015-11-30
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      相关资源
      最近更新 更多