【问题标题】:Regex match varying number of words正则表达式匹配不同数量的单词
【发布时间】:2023-04-05 06:40:01
【问题描述】:

软件 - Adob​​e Professional XI

编程 - 使用 正则表达式 匹配通配符的 JavaScript

背景 - 我有多个带有标题栏的 pdf 图纸,使用 java 脚本,根据单词 (通过与正则表达式匹配) 的位置添加数字签名字段。

目前正在测试图形标题栏的修订版 1 中是否存在文字。

脚本搜索修订号 1,后跟日期、标题(字数不同)和 4 组首字母。

数字 1 是静态的(日期、标题和首字母都是通配符,因为它们对于每张图纸都不同)。

我正在使用正则表达式来匹配单词。

这部分正则表达式查找数字 1 和日期(这是有效的)。

^1\s[0-9]{1,2}.[0-9]{1,2}.[0-9]{2}

正则表达式的其余部分与标题和首字母不匹配(这不起作用)

s\w+(\s+\w+){1,8}

如果有人可以帮助使用正则表达式来匹配最受赞赏的单词和首字母。

一旦正则表达式匹配工作,将在 4 组首字母的每个位置拆分,以便 javascript 可以在这些位置添加数字签名字段。

是否也可以就如何使用正则表达式拆分单词提供帮助?

这是整个脚本(javascript 正在运行,仅正则表达式需要帮助)

numWords = this.getPageNumWords(0);
// number of words on page
// loop through the words on page
for (var j = 0; j < numWords-1; j++)
{ // get word pair to test 
    ckWords = this.getPageNthWord(0, j) + ' ' + this.getPageNthWord(0, j + 1); // test words 

    // example of word string
    // 1 26.05.16 THE REINFORCEMENT REVISED MM SB AE GM

    if (ckWords.match(/^1\s[0-9]{1,2}.[0-9]{1,2}.[0-9]{2}\s\w+(\s+\w+){1,8}/))
    {
        console.println(ckWords);
    }
}

pdf of title block with text

【问题讨论】:

  • 您是否考虑过使用 split() 代替 reg ex?然后,如果需要,您可以分别对每个单词执行正则表达式或任何其他测试。
  • 你能像这样匹配字符串的背面吗? (\s+\w\w){1,4}$你只想要缩写,对吧?

标签: javascript regex


【解决方案1】:

将首字母添加到正则表达式的末尾,以便您可以分别匹配它们。

ckWords = '1 26.05.16 THE REINFORCEMENT REVISED MM SB AE GM';

match = ckWords.match(/^1\s\d{1,2}\.\d{1,2}\.\d{2}\s\w+(?:\s+\w+){1,8}\s([A-Z]{2})\s([A-Z]{2})\s([A-Z]{2})\s([A-Z]{2})$/);
console.log(match);

这会将首字母放入比赛的第 1 到第 4 组。

另外,不要忘记.在正则表达式中有特殊含义,所以你需要对它们进行转义以显式匹配它们。

【讨论】:

  • 正则表达式不能作为一个整体工作,我已经测试了最后带有首字母的部分。正则表达式需要找到
  • /**错误访问属性**/ 我还在原始帖子的末尾添加了一张图片,所以你会看到文本在标题块中并不完全是一个句子,但是在之后将文本从 pdf 复制并粘贴到记事本中,其中包含单词之间的空格(也非常感谢您花时间帮助我)
  • 我不知道this.getPageNthWord() 做了什么,但它似乎没有按照您在问题中显示的方式构建字符串。
  • 这似乎是与正则表达式完全不同的问题。如果您能弄清楚如何使字符串像您所显示的那样,则正则表达式将起作用。
  • 你是对的,你的正则表达式应该可以工作,我需要重新编程 this.getPageNthWord()。我会尝试用 javascript 解决这个问题,如果我能让它工作,我会回复你。再次感谢您抽出宝贵时间帮助我。
【解决方案2】:

这是否与您要查找的内容相近?

// some string with variable spaces and variable number of title words
var words = '1    26.05.16  THE   REINFORCEMENT  REVISED    MM  SB   AE  GM';

// match for:
// possible spaces at the start
// a 1
// variable spaces
// a xx.xx.xx date
// variable spaces
// any number of words that are not the initials, separated by variable spaces
// variable spaces
// four initials, separated by variable spaces
// possible spaces at the end
var matches = words.match(/^\s*1\s+\d\d\.\d\d\.\d\d\s+((?:\w+\s+)+\w+)\s+([A-Z]{2})\s+([A-Z]{2})\s+([A-Z]{2})\s+([A-Z]{2})\s*$/);
console.log(matches);

// replace variable spaces in title with single spaces
console.log(matches[1]);
matches[1] = matches[1].replace(/\s+/g, ' ');
console.log(matches[1]);

【讨论】:

    猜你喜欢
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多