How can I remove all leading and trailing punctuation?

让人想犯罪 __ 提交于 2019-12-01 18:19:49

Ok. So basically you want to find some pattern in your string and act if the pattern in matched.

Doing this the naiive way would be tedious. The naiive solution could involve something like

while(myString.StartsWith("." || "," || ";" || ...)
  myString = myString.Substring(1);

If you wanted to do a bit more complex task, it could be even impossible to do the way i mentioned.

Thats why we use regular expressions. Its a "language" with which you can define a pattern. the computer will be able to say, if a string matches that pattern. To learn about regular expressions, just type it into google. One of the first links: http://www.codeproject.com/Articles/9099/The-30-Minute-Regex-Tutorial

As for your problem, you could try this:

myString.replaceFirst("^[^a-zA-Z]+", "")

The meaning of the regex:

  • the first ^ means that in this pattern, what comes next has to be at the start of the string.

  • The [] define the chars. In this case, those are things that are NOT (the second ^) letters (a-zA-Z).

  • The + sign means that the thing before it can be repeated and still match the regex.

You can use a similar regex to remove trailing chars.

myString.replaceAll("[^a-zA-Z]+$", "");

the $ means "at the end of the string"

Use this tutorial on patterns. You have to create a regex that matches string starting with alphabet or number and ending with alphabet or number and do inputString.matches("regex")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!