匹配JS字符串与正则表达式

时间:2022-09-13 13:30:45

I have a long xml raw message that is being stored in a string format. A sample is as below.

我有一个长xml原始消息,以字符串格式存储。样品如下。

 <tag1>val</tag><tag2>val</tag2><tagSomeNameXYZ/>

I'm looking to search this string and find out if it contains an empty html tag such as <tagSomeNameXYZ/>. This thing is, the value of SomeName can change depending on context. I've tried using Str.match(/tagSomeNameXYZ/g) and Str.match(/<tag.*.XYZ\/>/g) to find out if it contains exactly that string, but am able to get it return anything. I'm having trouble in writing a reg ex that matches something like <tag*XYZ/>, where * is going to be SomeName (which I'm not interested in)

我正在寻找这个字符串,并找出它是否包含一个空的html标签,如 。这就是,SomeName的值可以根据上下文而改变。我尝试过使用Str.match(/ tagSomeNameXYZ / g)和Str.match(/ / g)来确定它是否包含该字符串,但是能够让它返回任何内容。我在编写一个与 匹配的reg ex时遇到了麻烦,其中*将是SomeName(我不感兴趣)

Tl;dr : How do I filter out <tagSomeNameXYZ/> from the string. Format being : <constant variableName constant/>

Tl; dr:如何从字符串中过滤出 。格式为:

Example patterns that it should match:

它应匹配的示例模式:

<tagGetIndexXYZ/>
<tagGetAllIndexXYZ/>
<tagGetFooterXYZ/>

1 个解决方案

#1


0  

The issue you have with Str.match(/<tag.*.XYZ\/>/g) is the .* takes everything it sees and does not stop at the XYZ as you wish. So you need to find a way to stop (e.g. the [^/]* means keep taking until you find a /) and then work back from there (the slice).

你对Str.match(/ / g)的问题是。*接受它所看到的一切,并且不会在你想要的XYZ停止。所以你需要找到一种方法来停止(例如[^ /] *意味着继续采取直到你找到一个/),然后从那里(切片)回来。

Does this help

这有帮助吗?

testString = "<tagGetIndexXYZ/>"
res = testString.match(/<tag([^/]*)\/\>/)[1].slice(0,-3)
console.log(res)

#1


0  

The issue you have with Str.match(/<tag.*.XYZ\/>/g) is the .* takes everything it sees and does not stop at the XYZ as you wish. So you need to find a way to stop (e.g. the [^/]* means keep taking until you find a /) and then work back from there (the slice).

你对Str.match(/ / g)的问题是。*接受它所看到的一切,并且不会在你想要的XYZ停止。所以你需要找到一种方法来停止(例如[^ /] *意味着继续采取直到你找到一个/),然后从那里(切片)回来。

Does this help

这有帮助吗?

testString = "<tagGetIndexXYZ/>"
res = testString.match(/<tag([^/]*)\/\>/)[1].slice(0,-3)
console.log(res)