简体   繁体   English

JavaScript:如何使用 RegEx 获取字符串中的特定文本

[英]JavaScript: How to get specific text in a string using RegEx

I tummbled into this RegEx and I googled it.我偶然发现了这个 RegEx 并用谷歌搜索了它。 A lot.很多。 But unfortunately didn't quite understand how RegEx works... So to make this quick since only a tiny winny part of my work requires it so I will be needing you guys.但不幸的是,我不太了解 RegEx 的工作原理......所以为了快速实现这一点,因为我的工作中只有一小部分需要它,所以我需要你们。 again :))再次 :))

So here it goes...所以就到这里了……

All I want is to retrieve a specific string with a format of 0000x0000 .我想要的只是检索格式为0000x0000的特定字符串。 For example:例如:

Input: NameName975x945NameName Output: 975x945输入: NameName975x945NameName输出: 975x945

Must also consider string like this: NameNameName9751x9451NameNameName (the integer and string are longer...)还必须考虑这样的字符串: NameNameName9751x9451NameNameName (整数和字符串更长...)

Use regex in String.prototype.match() to get specific part of string.String.prototype.match()使用正则表达式来获取字符串的特定部分。

str.match(/\d+x\d+/)[0]

 var str = "NameName975x945NameName"; var match = str.match(/\\d+x\\d+/)[0]; console.log(match)

We need a bit more detail, but I'll go in order:我们需要更多细节,但我会按顺序进行:

Assuming there can be any number of digits before and after the x, and these can be of different lengths:假设 x 前后可以有任意数量的数字,并且这些数字的长度可以不同:

[\\d]+x[\\d]+

Assuming the number of digits before the x needs to be equal to the number of digits after the x (as in your example) and this number is finite (and small enough so that your regex isn't obscenely long):假设 x 之前的位数需要等于 x 之后的位数(如您的示例中所示)并且这个数字是有限的(并且足够小,因此您的正则表达式不会太长):

[\\d]{1}x[\\d]{1}|[\\d]{2}x[\\d]{2}|[\\d]{3}x[\\d]{3} (and so on) [\\d]{1}x[\\d]{1}|[\\d]{2}x[\\d]{2}|[\\d]{3}x[\\d]{3} (等等在)

Check out this related answer for more details on handling this as the length of the number gets longer.随着数字的长度变长,请查看此相关答案以获取有关处理此问题的更多详细信息。

Then you can use String.prototype.match() with your regex to grab the matches within your string.然后你可以使用String.prototype.match()和你的正则表达式来获取字符串中的匹配项。

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

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