使用正则表达式查找Javascript中两个字符串之间的差异

编程入门 行业动态 更新时间:2024-10-07 14:31:50
本文介绍了使用正则表达式查找Javascript中两个字符串之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

请正则表达式专家帮忙看看这个问题是否可以通过正则表达式解决:

Regex experts please help to see if this problem can be solved by regex:

给定字符串 1 是任意字符串

Given string 1 is any string

字符串 2 是包含字符串 1 的所有部分的任何字符串(但不是简单的匹配——我举个例子)

And string 2 is any string containing all parts of string 1 (but not a simple match -- I will give example)

如何使用正则表达式将字符串 2 中字符串 1 的所有部分替换为空白,以便剩下的字符串不在字符串 1 中?

How to use regex to replace all parts of string 1 in string 2 with blank so that what's remained is the string not in string 1?

例如:str1 = "测试 xyz";str2 = "测试 ab xyz"

For example: str1 = "test xyz"; str2 = "test ab xyz"

我想要ab"或ab"回来.我可以编写什么正则表达式,以便在 str2 上运行替换函数时,它会返回ab"?

I want " ab" or "ab " back. What is the regex I can write so that when I run a replace function on str2, it will return " ab"?

这是一些非正则表达式代码:

Here is some non-regex code:

function findStringDiff(str1, str2) { var compareString = function(str1, str2) { var a1 = str1.split(""); var a2 = str2.split(""); var idx2 = 0; a1.forEach(function(val) { if (a2[idx2] === val) { a2.splice(idx2,1); } else { idx2 += 1; } }); if (idx2 > 0) { a2.splice(idx2,a2.length); } return a2.join(""); } if (str1.length < str2.length) { return compareString(str1, str2); } else { return compareString(str2, str1); } } console.log(findStringDiff("test xyz","test ab xyz"));

推荐答案

正则表达式仅识别字符串是否与特定模式匹配.它们不够灵活,无法像您要求的那样进行比较.您必须采用第一个字符串并基于它构建常规语言来识别第二个字符串,然后使用匹配组获取第二个字符串的其他部分并将它们连接在一起.这是一些以可读的方式完成我认为你想要的东西.

Regexes only recognize if a string matches a certain pattern. They're not flexible enough to do comparisons like you're asking for. You would have to take the first string and build a regular language based on it to recognize the second string, and then use match groups to grab the other parts of the second string and concatenate them together. Here's something that does what I think you want in a readable way.

//assuming "b" contains a subsequence containing //all of the letters in "a" in the same order function getDifference(a, b) { var i = 0; var j = 0; var result = ""; while (j < b.length) { if (a[i] != b[j] || i == a.length) result += b[j]; else i++; j++; } return result; } console.log(getDifference("test fly", "test xy flry"));

这是一个 jsfiddle:jsfiddle/d4rcuxw9/1/

Here's a jsfiddle for it: jsfiddle/d4rcuxw9/1/

更多推荐

使用正则表达式查找Javascript中两个字符串之间的差异

本文发布于:2023-11-30 13:34:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650169.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   差异   两个   正则表达式   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!