正则表达式在句子开头/结尾添加方括号,同时通过逗号分隔每个单词。

huangapple go评论80阅读模式
英文:

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]

huangapple
  • 本文由 发表于 2020年9月18日 03:14:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63944822.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定