如何解析以特定字符开头和结尾的字符串

时间:2019-03-05 19:34:22

标签: javascript parsing

我正在尝试使用Java解析以下字符串:

  

s_ev14 = cid = extCid-1:med = extMid-2:source = google:scode = RSG00000E017:campdesc = 123456789

需要注意的是(cid,med,source,scode,campdesc)可能会被打乱,在某些情况下可能不存在。话虽如此,我正在寻找拾起分配给这些标签的字符串。 这是我到目前为止的内容:

var Cid = input.substring(input.indexOf('cid=')+4,input.indexOf(':'));

并获得“ extCid-1”的输出,但是由于“:”出现在多个位置,因此我在解析其余变量时遇到了困难。

这是我的完整代码:

     <script type="text/javascript">_satellite.pageBottom();</script>

            <script type="text/javascript">
            window.addEventListener('message', function(event) {
                if (event.origin === "https://www.fdafadsfads.com"
                    || event.origin === "https://stage.rreasdfsd.com"
                    || event.origin === "https://stage-www.vderere.com"
                    || event.origin === "https://m.vereasre.com") { 
                    /* only accept messages from appropriate senders */
                    console.log('Supported origin: ' + event.origin); // comment later
                } else {
                    console.log('Unsupported orgin: ' + event.origin);  // comment later  
                    return;
                }
    //s_ev14=cid=extCid-1:med=extMid-2:source=google:scode=RSG00000E017:campdesc=123456789
                console.log("raw event.data: " + event.data);


                //Removes s_ev14 from the string
                //cid=extCid-1:med=extMid-2:source=google:scode=RSG00000E017:campdesc=123456789
                var SlicedData = event.data.slice(7);
                console.log("Sliced event data: " + SlicedData);


                const input = SlicedData; 

                const dictionary = {
                    cid: '',
                    med: '',
                    source: '',
                    scode: '',
                    campdesc: ''
                }

                const result = 
                    input.split(":")
                         .map(s => s.split("="))
                         .filter(o => !!o[1])
                         .reduce((dictionary, o) => {
                         dictionary[o[0]] = o[1]
                         return dictionary
                         }, dictionary)

                    const cid1 = result['cid']
                    const med1 = result['med']
                    const source1 = result['source']
                    const scode1 = result['scode']
                    const campdesc1 = result['campdesc']

console.log("Cid1: " + cid1);
            console.log("Med1: " + med1);
            console.log("Source1: " + source1);
            console.log("Scode1: " + scode1);
            console.log("Campdesc1: " + campdesc1);

3 个答案:

答案 0 :(得分:2)

编辑:OP标记为Java而不是JavaScript。由于var的语法相同,我们都感到困惑。

使用Stream的方法可能是

final String input = "s_ev14=cid=extCid-1:med=extMid-2:source=google:scode=RSG00000E017:campdesc=123456789";
final Map<String, String> attributes =
        Stream.of(input.substring(7).split(":"))
              .map(s -> s.split("=", 2))
              .filter(o -> o.length > 1)  // If you don't want empty values
              .collect(Collectors.toMap(o -> o[0], o -> o[1]));

输出

{scode=RSG00000E017, campdesc=123456789, source=google, med=extMid-2, cid=extCid-1}

如果您需要将每个值分配给一系列变量,只需

final var cid = attributes.get("cid");
final var med = attributes.get("med");
final var source = attributes.get("source");
final var campdesc = attributes.get("campdesc");

那是使用Java 10 +语法,看来您也在使用。


对于JavaScript版本

const input = "cid=extCid-1:med=extMid-2:source=:scode=RSG00000E017:campdesc=123456789"

// Default values
const dictionary = {
  cid: '',
  med: '',
  source: '',
  code: '',
  campdesc: ''
}

const result = 
    input.split(":")     // <-- Change the separator to & if needed
         .map(s => s.split("="))
         .filter(o => !!o[1])
         .reduce((dictionary, o) => {
            dictionary[o[0]] = o[1]
            return dictionary
         }, dictionary)  // <-- Default values as starting point

const cid = result['cid']
const med = result['med']
const source = result['source']
const code = result['code']
const campdesc = result['campdesc']

输出

{cid: "extCid-1", med: "extMid-2", scode: "RSG00000E017", campdesc: "123456789"}

答案 1 :(得分:0)

您可以使用String.split(":")方法来拆分给定字符串中的所有令牌,然后使用String.startsWithString.endsWith方法来实际获取单个令牌的值。

答案 2 :(得分:0)

您可以使用正则表达式:

String s = "s_ev14=cid=extCid-1:med=extMid-2:source=google:scode=RSG00000E017:campdesc=123456789";

Map<String, String> map = new TreeMap<>();
for (Matcher m = Pattern.compile("(\\w+)=([^:=]+)(?=:|$)").matcher(s); m.find(); )
    map.put(m.group(1), m.group(2));
map.entrySet().forEach(System.out::println);

输出

campdesc=123456789
cid=extCid-1
med=extMid-2
scode=RSG00000E017
source=google

更新

一旦解析为Map,它们很容易提取为变量:

String cid = map.get('cid');
String med = map.get('med');
String source = map.get('source');
String scode = map.get('scode');
String campdesc = map.get('campdesc');