2016-08-29 22 views
0

我正在使用PowerShell和MS Access。使用數學因子替換字符串的一部分

我想將數學因子應用於此列值中的管道內部。

Ex。 -100.0必須變成-400.0和100.0必須變成400.0,因爲因子是4.

我只需要修改「Min_Value」和「Max_Value」標記(硬編碼)。

FiledValue來自數據庫(有多行)。

FieldValue並不總是與此示例完全相同,但令牌模式始終與Ex相同。 MIN_VALUE = | ..... |

function Test 
{ 
$Factor = 4 

# Hard-coded SQL query result 
$FieldValue = "Min_Value=|-100.0|;Max_Value=|100.0|;COMM_ID1=|1|;" 

# Compare this value with a regular expression (Issue A: This doesn't work because of the minus sign and decimal) 
if ($FieldValue -match "Min_Value=\|([0-9]+)\|;Max_Value=\|([0-9]+)\|;") 
{ 
    # Trying to retreive -100.0 here...(Issue B: this doesn't work). I beleive I can only specify ||, not Min_Value=|| 
    $TokenMinValue = $FieldValue.Split('Min_Value=||')[1] 
    $TokenMaxValue = $FieldValue.Split('Max_Value=||')[1] 

    # Trying to take the token (-100.0), multiply it by 4 and write it back where I found it (Issue C: this obvioulsy doesn't work) 
    $Result = $FieldValue -replace "$regex",($TokenMinValue * $Factor) 
    $Result = $FieldValue -replace "$regex",($TokenMaxValue * $Factor) 

    #The goal is for $Result to equal "Min_Value=|-400.0|;Max_Value=|400.0|;COMM_ID1=|1|;" 
} 
} 
+0

是2和3甚至可以在SQL? – sln

+0

你的代碼在哪裏!你試過什麼了? – Marusyk

+0

下面是我如何解決它: $ factor = 25.4 $ minRegex =「Min_Value = \ |([ - ]?[0-9] * \。?[0-9] *)\ |;」 \t $ maxRegex =「Max_Value = \ |([ - ]?[0-9] * \。?〔0-9] *)\ |; 「$ 修飾的= 0 如果($ fieldValue方法-match $ minRegex) {\t \t \t \t \t $令牌= $匹配[1] $替換=」 MIN_VALUE = |」 +([轉換] :: ToDouble($令牌)* $因子)+ 「|」; $ fieldValue方法= $ fieldValue方法-replace $ minRegex,$替換\t $修飾的= 1 \t \t \t \t \t } //同上最大\t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t 如果($修飾的)//做UPDATE查詢 – Illuna

回答

1

您沒有指定您的DBMS,所以這裏是一個使用Postgres的解決方案。至少你可以遵循一個道理:

select 
    concat(
    replace(
     concat('Min_Value=|', string_agg(intval,';')), ';', '|;Max_Value=|'), 
    '|;') 
from (
    select (unnest(regexp_matches('Min_Value=|10|;Max_Value=|100|;', 'Min_Value=\|([0-9]+)\|;Max_Value=\|([0-9]+)\|;'))::int*4)::TEXT as intval 
) foo; 

,奇蹟發生了這樣的:

  1. regexp_matches提取兩位來自輸入字符串的整數
  2. 使用unnest解壓陣列分成兩個獨立的行
  3. 將這些整數值(此時爲文本)轉換爲Integer並乘以因子4
  4. 使用string_agg;作爲分隔符,使含有;
  5. 使用concat分隔開頭追加Min_Value=|兩個整數一個串排,所以現在的字符串是Min_Value=|40;400
  6. 使用replace,並與下一個零件替換; - |;Max_Value=|所以字符串現在是Min_Value=|40|;Max_Value=|400
  7. 使用concat再追加|;到字符串的結尾

輸入:

Min_Value=|10|;Max_Value=|100|; 

結果:

Min_Value=|40|;Max_Value=|400|; 
+0

謝謝您的anwser,我修改了我的問題是更多的目標。 – Illuna

+0

基本上沒有什麼作品從你發佈。請嘗試一下自己。基本的正則表達式知識將解決問題A.然後基本的Powershell知識將解決問題B ... –

相關問題