简体   繁体   English

regEx文本替换为| 和()捕获问题

[英]regEx text replace using | and () capture issue

I'm using javaScript RegEx literals to replace parts of a string, i want to use | 我正在使用javaScript RegEx文字替换字符串的一部分,我想使用| to check for different types of patterns that may occur and () to capture a part of the match i want to replace. 检查可能发生的不同类型的模式,以及()捕获我要替换的部分匹配内容。 it doesn't seem to work though, why is this? 它似乎没有用,为什么呢?

here's my current regEx: 这是我当前的regEx:

testText.replace(/(\w)\s+\w$|(\w)\s+$|\w+(\w)$/g, "$1...")

I'm guessing somethings wrong with it: here's want i want to acheieve: 我正在猜测它出了点问题:这是我想要实现的目标:

given "xx" i expect: 给定“ xx”,我期望:

  "x..."

given "x " I expect: 给定“ x”,我期望:

   "x...

given "werfdsdfasd" (word with no space) I expect: 给定“ werfdsdfasd”(没有空格的单词),我期望:

   "werfdsdfasd..."

The problem is that you have 3 capture groups and you always reference the first one. 问题是您有3个捕获组,并且始终引用第一个捕获组。

Try this: (\\w+)(?:\\s+\\w$|\\s+$|$) 试试这个: (\\w+)(?:\\s+\\w$|\\s+$|$)

Demo 演示

因此,您想捕获空格或行尾之前的所有内容。

(\w+)(\s+.*$|$)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM