首页 > 解决方案 > 您如何区分运算符与知道它不是运算符但属于字符串?

问题描述

例如,这是字符串:
“你好,这很有挑战性\n”+“你认为这很容易吗?\n”+ variableName +“3 + 4 = 7\n”

Dim example = """Hello, this is challenging\n"" + ""you think it is easy?\n"" + variableName + "" 3 + 4 = 7\n"""

我想用编程的方式来排列字符串变成:
“你好,这很有挑战性”+换行符+“你觉得这很容易吗?” + 换行符 + 变量名 + " 3 + 4 = 7" + 换行符

Dim output = """Hello, this is challenging"" + newline + ""you think it is easy?"" + newline + variableName + "" 3 + 4 = 7"" + newline"

如您所见,它涉及获取引号内的文本
所以我在想:
1. 使用正则表达式来获取引号,但是正如您所看到的,我们将省略变量名
2. 我正在考虑使用 + 号拆分,但如您所见,“3 + 4 = 7”中会有误报

告诉我你怎么看,容易吗?还有其他步骤吗?


更新的示例和输出:

Dim example2 = """Hello, this \nis challenging\n"" + ""you think it is easy?\n"" + variableName + "" 3 + 4 = 7\n"""

Dim output2 = """Hello, this "" + newline + ""is challenging"" + newline + ""you think it is easy?"" + newline + variableName + "" 3 + 4 = 7"" + newline"

标签: vb.netvb.net-2010vb.net-module

解决方案


这个单线对我有用:

Dim example = """Hello, this is challenging\n"" + ""you think it is easy?\n"" + variableName + "" 3 + 4 = 7\n"""
Dim output = """Hello, this is challenging"" + newline + ""you think it is easy?"" + newline + variableName + "" 3 + 4 = 7"" + newline"

Dim result = String.Join("""", example.Split(""""c).Select(Function(x, n) If(n Mod 2 = 1, x.Replace("\n", """ + newline"), x))).Replace("newline""", "newline")

我和你的输出一样。


这是更新的示例工作正常:

Dim example2 = """Hello, this \nis challenging\n"" + ""you think it is easy?\n"" + variableName + "" 3 + 4 = 7\n"""
Dim output2 = """Hello, this "" + newline + ""is challenging"" + newline + ""you think it is easy?"" + newline + variableName + "" 3 + 4 = 7"" + newline"
Dim result2 = String.Join("""", example2.Split(""""c).Select(Function(x, n) If(n Mod 2 = 1, x.Replace("\n", """ + newline + """), x))).Replace("newline + """"", "newline")

"Hello, this " + newline + "is challenging" + newline + "you think it is easy?" + newline + variableName + " 3 + 4 = 7" + newline按照你的得到output2


这是发生了什么result2

Dim splitOnQuotes = example2.Split(""""c)
'splitOnQuotes = { "", "Hello, this \nis challenging\n", " + ", "you think it is easy?\n", " + variableName + ", " 3 + 4 = 7\n", "" }

所有的双引号都被拆分了。

Dim replaceSlashNOnOddLines = splitOnQuotes.Select(Function(x, n) If(n Mod 2 = 1, x.Replace("\n", """ + newline + """), x))
'replaceSlashNOnOddLines = { "", "Hello, this " + newline + "is challenging" + newline + "", " + ", "you think it is easy?" + newline + "", " + variableName + ", " 3 + 4 = 7" + newline + "", "" }

在我们用 替换的每个奇数元素\n" + newline + "

Dim joinOnQuotes = String.Join("""", replaceSlashNOnOddLines)
'joinOnQuotes = "Hello, this "" + newline + ""is challenging"" + newline + """" + ""you think it is easy?"" + newline + """" + variableName + "" 3 + 4 = 7"" + newline + """""

然后加入备份的部分 "

Dim result2 = joinOnQuotes.Replace("newline + """"", "newline")

但是我们有额外的双引号,形式为newline + "",所以我们只需将它们替换为newline


推荐阅读