I have one input String
like this:
"I am Duc/N Ta/N Van/N"
String "/N"
present it is the Name of one person.
The expected output is:
Name: Duc Ta Van
How can I do it by using regular expression?
I have one input String
like this:
"I am Duc/N Ta/N Van/N"
String "/N"
present it is the Name of one person.
The expected output is:
Name: Duc Ta Van
How can I do it by using regular expression?
Here is the regex to use to capture every "name" preceded by a /N
(\w+)\/N
Validate with Regex101
Now, you just need to loop on every match in that String
and concatenate the to get the result :
String pattern = "(\\w+)\\/N";
String test = "I am Duc/N Ta/N Van/N";
Matcher m = Pattern.compile(pattern).matcher(test);
StringBuilder sbNames = new StringBuilder();
while(m.find()){
sbNames.append(m.group(1)).append(" ");
}
System.out.println(sbNames.toString());
Duc Ta Van
It is giving you the hardest part. I let you adapt this to match your need.
Note :
In java, it is not required to escape a forward slash, but to use the same regex in the entire answer, I will keep "(\\w+)\\/N"
, but "(\\w+)/N"
will work as well.
You can use Pattern and Matcher like this :
String input = "I am Duc/N Ta/N Van/N";
Pattern pattern = Pattern.compile("([^\\s]+)/N");
Matcher matcher = pattern.matcher(input);
String result = "";
while (matcher.find()) {
result+= matcher.group(1) + " ";
}
System.out.println("Name: " + result.trim());
Output
Name: Duc Ta Van
From Java9+ you can use Matcher::results
like this :
String input = "I am Duc/N Ta/N Van/N";
String regex = "([^\\s]+)/N";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
String result = matcher.results().map(s -> s.group(1)).collect(Collectors.joining(" "));
System.out.println("Name: " + result); // Name: Duc Ta Van
I've used "[/N]+" as the regular expression.
[]
= Matches characters inside the set
\/
= Matches the character /
literally (case sensitive)
+
= Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)