計算字串中數字的個數這可能是一個非常具體的問題,但我的 JMP 單元格中包含一個字串,並且我需要能夠隔離字串中數字字元的特定段落。該字串包含字元和數字,且序列可以是可變的。例如,如果我有單元格條目
AAA1B222C3
我想將第 222 個段落歸零,我考慮了一種方法來將數字段落的數量計算為 3,然後隔離其中的第二個。
我想出了一種使用正規表示式來做到這一點的方法,但它太複雜了,不值得發布。我確信有一種更具適應性的方式可以實現這一目標。所有想法都受到讚賞。
再見
扳手頭
自動化和腳本編寫Re: 計算字串中數字的個數您能否提供更多可能的字串和您希望隔離的部分的範例?另外你想用這些零件做什麼?提取它們?刪除它們?檢查是否存在?
Re: 計算字串中數字的個數雅爾莫
我的總體目標是建立一個新列,其中包含作為單元格輸入的數值。這是因為原始條目包含維度信息,並且我希望該信息能夠自動以數字形式提供。數位通道之一是長度,另一個是寬度。還有其他數字,我需要一種方法來繞過這些數字。實際的字串看起來更接近
瓦爾1b200X300
這是一個 200 長 x 300 寬的設備,我需要包含生成的反映這些值的單元格的新列。附加數字字元的長度或位置不一致,這增加了任務的複雜性。
再見
扳手頭
Re: 計算字串中數字的個數這些總是三個字元長嗎?它們總是最後兩個數字嗎?它們總是用“X”分隔嗎?
Re: 計算字串中數字的個數雅爾莫
部分違反了墨菲定律。長度並不總是相同,也不總是最後 2 個數字,但總是用 X 分隔。
再見
扳手頭
Re: 計算字串中數字的個數這可能就足夠了,或者您可能需要添加一些額外的條件(檢查它是否在開始/結束或之前/之後有字母)
Names Default To Here(1);
str = "Val1b200X300abcc1";
r = Regex Match(str, "(\d+)X(\d+)");
Show(Num(r[2]), Num(r[3]));
Re: 計算字串中數字的個數雅爾莫
很棒的東西!這就是我最終想到的。標籤是包含我要對其進行手術的字串的列。
New Column("Width", Character, "Nominal", Formula(Regex(:Label, "(\d+)X", "\1")), Set Selected);
New Column("Length", Character, "Nominal", Formula(Regex(:Label, "X(\d+)", "\1")), Set Selected);
似乎有效。
再見
扳手頭
Re: 計算字串中數字的個數這取決於您的數據,但您可能想要在正規表示式模式中添加一個小補充:在 X 的另一側添加對其他數字的檢查,以避免類似「1Xa」的問題
Names Default To Here(1);
strs = {"A1X2", "A1Xa", "1X2", "a1X23", "aX2", "A1X2a"};
For Each({str}, strs,
a1 = Regex(str, "(\d+)X", "\1");
a2 = Regex(str, "X(\d+)", "\1");
// vs
b1 = Regex(str, "(\d+)X(\d+)", "\1");
b2 = Regex(str, "(\d+)X(\d+)", "\2");
Write("\!NCurrent string: ", str);
Write("\!NFirst pattern matches: ", a1, " ", a2);
Write("\!NSecond pattern matches: ", b1, " ", b2);
Write("\!N");
);
Current string: A1X2
First pattern matches: 1 2
Second pattern matches: 1 2
Current string: A1Xa
First pattern matches: 1 .
Second pattern matches: . .
Current string: 1X2
First pattern matches: 1 2
Second pattern matches: 1 2
Current string: a1X23
First pattern matches: 1 23
Second pattern matches: 1 23
Current string: aX2
First pattern matches: . 2
Second pattern matches: . .
Current string: A1X2a
First pattern matches: 1 2
Second pattern matches: 1 2
Re: 計算字串中數字的個數另外,我對最初問題的第一個理解是從字串中提取最長的數字序列,因此這裡有幾個腳本(可能對某人有用)。
1.使用Words()(類似的想法可以用來提取非數字字串)
Names Default To Here(1);
str = "aaa1b222c3";
alphabets = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
nums = Words(str, alphabets);
lengths = Transform Each({num}, nums, Output("Matrix"), Length(num));
l_idx = Loc Max(lengths);
longest_num_seq = nums[l_idx];
show(nums, longest_num_seq); //nums = {"1", "222", "3"}, longest_num_seq = "222";
2. 使用 While + 正規表示式
Names Default To Here(1);
str = "aaa1b222c3";
nums = {};
strcopy = str;
While(!IsMissing(match = Regex(strcopy, "\d+")),
idx = Contains(strcopy, match);
Insert Into(nums, match);
Remove From(strcopy, idx, Length(match));
);
l_idx = Loc Max(lengths);
longest_num_seq = nums[l_idx];
show(nums, longest_num_seq); //nums = {"1", "222", "3"}, longest_num_seq = "222";