【发布时间】:2018-01-30 13:46:01
【问题描述】:
我有一个字符串
String me = "I am ugly and not handsome."
我想成功
I am ugly, not handsome.
所以我需要将 " 和 " 替换为 "、"。据说我可以用
String.replace(" and ", ", ")
但是,它会忽略空格并查找 and 的所有实例。所以会发生这种情况:
I am ugly, not h,dsome
我在字符串解析程序中使用它。它迭代了数千行,所以我希望它能够提高速度。我不知道我所做的是否是“速度高效”,或者如果您有任何其他意见我会很感激。 示例文件:
[and & , , , --- 1] (datetime)
[and & , , , --- 2] (datetime) - You are kind
[and & , , , --- 3] (datetime) - word1, word2 & wor&d3
[and & , , , --- 4] (Datetime) - word1, word2andword3, and word3
为了清楚说明我为什么要实现这一目标,以防万一有人有更好的解决方案: 我正在从事的项目需要将其解析为 Json:
[
{
"message":"and & , , , --- 1",
"timestamp":"datetime",
"content":[]
},
{
"message":"and & , , , --- 2",
"timestamp":"datetime",
"content":[{"text":"You are kind"}]
},
{
"message":"and & , , , --- 3",
"timestamp":"datetime",
"content":[{"text":"word1"},{"text":"word2"},{"text":"wor&d3"}]
},
{
"message":"and & , , , --- 4",
"timestamp":"datetime",
"content":[{"text":"word1"},{"text":"word2andword3"},{"text":"word3"}]
},
]
目前,我通过逐行迭代文件并将该行解析为实体来解析它。但是我相信当格式不遵循所需的解析器格式时,这会给我带来未来的问题。
【问题讨论】:
-
试过使用正则表达式吗?
-
只需替换“我很丑”和“我很丑”,
-
无法重现此行为。我得到“我很丑,不帅”。结果如你所愿。
-
你能添加更多的代码细节,“和”,不会省略空格我的默认
-
使用
String.replace(" \\s and \\s ", ", ")