英文:
Regex to add square brackets into beginning/end sentence and also each word separate by comma?
问题
我需要使用什么样的正则表达式来在句子开头/结尾添加方括号,并且用逗号分隔每个单词?
我有一个像这样的句子:
qqqqqqq\
asadsds\
dsdadad\
sadadad\
asdsada\
dsadadd";
我期望得到如下结果:
[qqqqqq, asadsds, dsdadad, sadadad, asdsada, dsadadd]
我尝试了很多方法,比如:
String regex1 = "(^[a-zA-z_0-9])(\\s)([a-zA-z_0-9]$)";
英文:
What kind of regex do I need to use to add square brackets into beginning/end sentence and also each word separate by comma?
I have a sentence like this:
qqqqqqq\
asadsds\
dsdadad\
sadadad\
asdsada\
dsadadd";
I expecting to get result like this:
[qqqqqq, asadsds, dsdadad, sadadad, asdsada, dsadadd]
I try many things such as:
String regex1 = "(^[a-zA-z_0-9])(\\s)([a-zA-z_0-9]$)";
答案1
得分: 1
似乎您需要将输入字符串拆分成一些“单词”,因此需要使用 `String.split("\\W+")` 或 `String.split("[^a-zA-Z]+")` 来排除所有非字母字符或非单词字符作为分隔符。
然后,使用逗号重新连接清理后的单词,并添加括号,这可以通过 `Arrays.toString` 方法提供。
这可以简单实现如下:
```java
String input = "qqqqqqq\\\nasadsds\\\ndsdadad\\\nsadadad\\\nasdsada\\\ndsadadd\";";
System.out.println(input);
System.out.println("------------");
String result = Arrays.toString(input.split("\\W+"));
System.out.println(result);
输出:
qqqqqqq\
asadsds\
dsdadad\
sadadad\
asdsada\
dsadadd";
------------
[qqqqqqq, asadsds, dsdadad, sadadad, asdsada, dsadadd]
英文:
It seems that you need to split the input string into some "words" thus excluding all non-letter or non-word characters as delimiters using String.split("\\W+")
or String.split("[^a-zA-Z]+")
.
Then re-join the cleaned words using commas and adding brackets which can be provided by Arrays.toString
method.
This can be implemented simply:
String input = "qqqqqqq\\\nasadsds\\\ndsdadad\\\nsadadad\\\nasdsada\\\ndsadadd\";";
System.out.println(input);
System.out.println("------------");
String result = Arrays.toString(input.split("\\W+"));
System.out.println(result);
Output:
qqqqqqq\
asadsds\
dsdadad\
sadadad\
asdsada\
dsadadd";
------------
[qqqqqqq, asadsds, dsdadad, sadadad, asdsada, dsadadd]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论