[英]RegEx to replace entire string with first two values
I'm trying to come up with a regex expression to replace an entire string with just the first two values.我试图想出一个正则表达式来用前两个值替换整个字符串。 Examples:例子:
Entire String: AO SMITH 100108283 4500W/240V SCREW-IN ELEMENT, 11"整根琴弦:AO SMITH 100108283 4500W/240V 旋入式元件,11"
First Two Values: AO SMITH前两个值:AO SMITH
Entire String: BRA14X18HEBU / P11-042 / 310-470NL BRASS 1/4 x 1/8 HEX BUSHING整根弦:BRA14X18HEBU / P11-042 / 310-470NL BRASS 1/4 x 1/8 HEX BUSHING
First Two Values: BRA14X18HEBU / P11-042前两个值:BRA14X18HEBU / P11-042
Entire String: TWO-HOLE PIPE STRAP 4" 008004EG 72E 4整根弦:两孔 PIPE 表带 4" 008004EG 72E 4
First Two Values: TWO-HOLE PIPE前两个值:TWO-HOLE PIPE
The caveat is I'm wanting to preserve any kind of special characters and not count them, like "/"'s and "-"'s.需要注意的是,我想保留任何类型的特殊字符而不是计算它们,例如“/”和“-”。 The current code I've written does not, instead leaves the new values entirely blank.我编写的当前代码没有,而是将新值完全留空。 Only the first example above works.只有上面的第一个例子有效。
Here's what I've got so far:这是我到目前为止所得到的:
Matching Value:匹配值:
^(\w+) +(\w+).+$
New Value:新价值:
$1 $2
One option could be using a single capture group and use that in the replacement.一种选择是使用单个捕获组并在替换中使用它。
^(\w+(?:-\w+)?(?: +\/)? +\w+(?:-\w+)?).+
The pattern matches:模式匹配:
^
Start of string ^
字符串开头(
Capture group 1 (
捕获组 1
\w+(?:-\w+)?
Match 1+ word charss with an optional part to match a -
and 1+ word chars将 1+ 个单词字符与可选部分匹配以匹配-
和 1+ 个单词字符(?: +\/)?
Optionally match /
可选匹配/
+\w+(?:-\w+)?
Match 1+ word charss with an optional part to match a -
and 1+ word chars将 1+ 个单词字符与可选部分匹配以匹配-
和 1+ 个单词字符)
Close group 1 )
关闭第 1 组.+
Match 1+ times any char (the rest of the line) .+
匹配任何字符的 1+ 次(该行的 rest) If there can be more than 1 hyphen, you can use *
instead of ?
如果可以有超过 1 个连字符,您可以使用*
代替?
Output Output
AO SMITH
BRA14X18HEBU / P11-042
TWO-HOLE PIPE
A broader match could be matching non word chars in between the words更广泛的匹配可能是匹配单词之间的非单词字符
^(\w+(?:-\w+)*[\W\r\n]+\w+(?:-\w+)*).+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.