How to remove all leading and trailing punctuation marks?

I want to remove all leading and trailing punctuation marks in a string. How can i do this?

Basically, I want to keep the punctuation between words, and I need to remove all leading and ending punctuation marks.

  • . , @ , _ , & , / , - allowed if they are surrounded by letters or numbers
  • \' allowed if preceded by a letter or number

I tried

 Pattern p = Pattern.compile("(^\\p{Punct})|(\\p{Punct}$)"); Matcher m = p.matcher(term); boolean a = m.find(); if(a) term=term.replaceAll("(^\\p{Punct})", ""); 

but it didn’t work !!

+4
source share
2 answers

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

Performing this naive path would be tedious. A naive solution may include something like

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

If you want to do a more difficult task, it may even be impossible to do as I mentioned.

This is why we use regular expressions. Its "language" with which you can define a pattern. the computer can tell if the string matches this pattern. To learn about regular expressions, just enter it on Google. One of the first links: http://www.codeproject.com/Articles/9099/The-30-Minute-Regex-Tutorial

As for your problem, you can try the following:

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

Regex value:

  • the first ^ means that in this pattern what comes next should be at the beginning of the line.

  • [] define characters. In this case, these are things that are NOT (second ^) letters (a-zA-Z).

  • The + sign means that the thing in front of it can be repeated and is still consistent with the regular expression.

You can use a similar regular expression to remove trailing characters.

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

$ means "end of line"

+8
source

Use this template tutorial. You must create a regular expression that matches a line starting with an alphabet or number and ending with an alphabet or number, and inputString.matches("regex")

+1
source

Source: https://habr.com/ru/post/1435190/


All Articles