【问题标题】:Regular expression to match word pairs joined with colons正则表达式匹配用冒号连接的词对
【发布时间】:2017-04-06 11:34:52
【问题描述】:

我根本不知道正则表达式。任何人都可以帮助我使用一个非常简单的正则表达式,即,

从句子中提取“word:word”。例如“Java 教程 Format:Pdf With Location:Tokyo Javascript”?

  • 小修改: 第一个“单词”来自列表,但第二个是任何东西。 "[ABC, FGR, HTY] 中的 word1"
  • 伙计们的情况需要多一点 修改。 匹配形式可以是“word11:word12 word13 ..”直到下一个“word21:...”。

sec 的事情变得越来越复杂.....我必须学习 reg ex :(

提前致谢。

【问题讨论】:

    标签: regex


    【解决方案1】:

    您可以使用正则表达式:

    \w+:\w+
    

    解释:
    \w - 单个字符,可以是字母(大写或小写)、数字或 _。
    \w+ - 上述一个或多个字符..基本上是一个单词

    所以\w+:\w+ 将匹配以冒号分隔的一对单词。

    【讨论】:

      【解决方案2】:

      试试\b(\S+?):(\S+?)\b。第 1 组将捕获“格式”,第 2 组将捕获“Pdf”。

      一个工作示例:

      <html>
      <head>
      <script type="text/javascript">
      function test() {
          var re = /\b(\S+?):(\S+?)\b/g; // without 'g' matches only the first
          var text = "Java Tutorial Format:Pdf With Location:Tokyo  Javascript";
      
          var match = null;
          while ( (match = re.exec(text)) != null) {
              alert(match[1] + " -- " + match[2]);
          }
      
      }
      </script>
      </head>
      <body onload="test();">
      
      </body>
      </html>
      

      正则表达式的一个很好的参考是https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp

      【讨论】:

      • +1 表示完整的示例,但 -1 表示正则表达式,因为它本身就太复杂了。 ;)
      【解决方案3】:

      使用这个 sn-p :

      $str="这是pavun:kumar hello world bk:systesm"; if ( preg_match_all ( '/(\w+\:\w+)/',$str ,$val ) ) { print_r ( $val ) ; } 别的 { 打印“不匹配\n”; }

      【讨论】:

        【解决方案4】:

        根据您的额外要求继续 Jaú 的功能:

        function test() {
            var words = ['Format', 'Location', 'Size'],
                    text = "Java Tutorial Format:Pdf With Location:Tokyo Language:Javascript", 
                    match = null;
            var re = new RegExp( '(' + words.join('|') + '):(\\w+)', 'g');
            while ( (match = re.exec(text)) != null) {
                alert(match[1] + " = " + match[2]);
            }
        }
        

        【讨论】:

          【解决方案5】:

          我目前正在我的 nodejs 应用程序中解决这个问题,发现这是,我猜,适合冒号配对的措辞:

          ([\w]+:)("(([^"])*)"|'(([^'])*)'|(([^\s])*))
          

          它也匹配引用的值。喜欢a:"b" c:'d e' f:g

          es6 中的示例编码:

          const regex = /([\w]+:)("(([^"])*)"|'(([^'])*)'|(([^\s])*))/g;
          const str = `category:"live casino" gsp:S1aik-UBnl aa:"b" c:'d e' f:g`;
          let m;
          
          while ((m = regex.exec(str)) !== null) {
             // This is necessary to avoid infinite loops with zero-width matches
             if (m.index === regex.lastIndex) {
                regex.lastIndex++;
             }
          
             // The result can be accessed through the `m`-variable.
             m.forEach((match, groupIndex) => {
                console.log(`Found match, group ${groupIndex}: ${match}`);
             });
          }
          

          PHP 中的示例编码

          $re = '/([\w]+:)("(([^"])*)"|\'(([^\'])*)\'|(([^\s])*))/';
          $str = 'category:"live casino" gsp:S1aik-UBnl aa:"b" c:\'d e\' f:g';
          
          preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
          
          // Print the entire match result
          var_dump($matches);
          

          您可以使用此在线工具检查/测试您的正则表达式:https://regex101.com

          顺便说一句,如果没有被 regex101.com 删除,您可以浏览该示例编码here

          【讨论】:

            【解决方案6】:

            这是非正则表达式的方式,用你最喜欢的语言,在空格上分割,遍历元素,检查 ":" ,如果找到就打印它们。例如 Python

            >>> s="Java Tutorial Format:Pdf With Location:Tokyo Javascript"
            >>> for i in s.split():
            ...     if ":" in i:
            ...         print i
            ...
            Format:Pdf
            Location:Tokyo
            

            您可以通过在“:”上再次拆分并检查拆分列表中是否有 2 个元素来进行进一步检查以确保其确实是“someword:someword”。例如

            >>> for i in s.split():
            ...     if ":" in i:
            ...         a=i.split(":")
            ...         if len(a) == 2:
            ...             print i
            ...
            Format:Pdf
            Location:Tokyo
            

            【讨论】:

              【解决方案7】:
              ([^:]+):(.+)
              

              含义:(除 : 一次或多次之外的所有内容),:,(任何字符一次或多次)

              你会在网上找到很好的手册...也许是时候学习了...

              【讨论】:

              • 不起作用:使用这个简单的输入:"ab cd:ef gh" 你将匹配 'ab cd' 和 'ef gh' 而不是 'cd' 和 'ef'
              • 这个正则表达式非常错误,你也可以好好利用手册。
              • 不明白,抱歉。但是正则表达式有效,您只需按以下方式调整它: ([^:\s]+):([^\s]+)
              猜你喜欢
              • 2018-12-16
              • 2018-02-11
              • 1970-01-01
              • 1970-01-01
              • 2013-01-04
              • 1970-01-01
              • 1970-01-01
              • 2016-07-11
              相关资源
              最近更新 更多