从多行文字中获取第一个修剪的字符串

Get first trimmed strings from a multiline text

本文关键字:第一个 修剪 字符串 获取 文字      更新时间:2023-09-26

我的多行输入string:

123
 2345 a
ab_cd: xxxx
   123abc     456
:y

我想要得到的是模式[0-9a-z_]{1,100}适合的每一行的第一个匹配——忽略开头的空白和空行。

所以我预期的结果是:

123
2345
ab_cd
123abc

我的模式似乎不起作用:

$entries = string.match(/^(?:'s*)([a-z0-9_]{1,100})(?:.*)$/gm);    

非捕获组似乎被忽略了。我得到:

[ "123", " 2345 a", " ab_cd: xxxx", "   123abc     456" ]

只有:y被正确忽略。我在这里做错了什么?虽然我添加了这个标签,但我想这不是JS的问题。。。

编辑:我很乐意用regex模式解决问题,而不是用JS方式。

您可以使用

/^[ 't]*([0-9a-z_]{1,100})/gm

并获取第1组中的值。

如果你还需要匹配大写字母,只需使用

/^[ 't]*('w{1,100})/gm
         ^^

查看regex演示

var re = /^[ 't]*('w{1,100})/gm; 
var str = '123'n 2345 a'n'nab_cd: xxxx'n   123abc     456'n:y';
var res = [];
while ((m = re.exec(str)) !== null) {
    res.push(m[1]);
}
document.body.innerHTML = "<pre>" + JSON.stringify(res, 0, 4) + "</pre>";

模式详细信息:它使用/gm标志-全局和多行修饰符来匹配模式可以找到的所有子字符串,并使^与行的开头匹配。

  • ^—线路起点
  • [ 't]*-0+空格或制表符
  • ([0-9a-z_]{1,100})-第1组:1到100个字母、数字或_。如果大写字母也要匹配,请改用'w

正则表达式可以看起来像:

/^['s]*(['da-z_]{1,100})/gm

Regex101演示


Regex解释:

^ assert position at start of a line
['s]* match a single character present in the list below
    Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
    's match any white space character ['r'n't'f ]
1st Capturing group ([0-9a-z_]{1,100})
    [0-9a-z_]{1,100} match a single character present in the list below
        Quantifier: {1,100} Between 1 and 100 times, as many times as possible, giving back as needed [greedy]
        0-9 a single character in the range between 0 and 9
        a-z a single character in the range between a and z (case sensitive)
        _ the literal character _
m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
g modifier: global. All matches (don't return on first match)

您可以使用拆分修剪连接公式

var output = string.split("'n").map( function(val){
  return val.trim()
}).join("'n");

更多跨平台方式(同时兼顾'r

var output = string.replace(/'r'n/g,"'n").split("'n").map( function(val){
  return val.trim()
}).join("'n");