本文介绍了如何删除所有前导和尾随标点符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除字符串中的所有前导和尾随标点符号。我该怎么做?

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

基本上,我想在单词之间保留标点符号,我需要删除所有前导和尾随标点符号。

Basically, I want to preserve punctuation in between words, and I need to remove all leading and trailing punctuation.


  1. @ _ & / - 或数字

  2. \',则允许使用code>字母或数字

  1. ., @, _, &, /, - are allowed if surrounded by lettersor digits
  2. \' is allowed if preceded by a letter or digit

我试过

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

但它没有用!!

推荐答案

好的。所以基本上你想在你的字符串中找到一些模式,并且如果匹配的模式就行动。

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

这样做的方式很简单。 naiive解决方案可能涉及类似

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.

这就是我们使用正则表达式的原因。它是一种语言你可以定义一个模式。计算机将能够说,如果一个字符串匹配该模式。要了解正则表达式,只需将其输入谷歌。第一个链接之一: http://www.codeproject.com/Articles/9099/The-30-Minute-Regex-Tutorial

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]+", "")

正则表达式的含义:


  • 第一个^意味着在这个模式中,wha接下来必须是
    字符串的开头。

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

[]定义字符。在这种情况下,那些是非
(第二个^)字母(a-zA-Z)的东西。

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

您可以使用类似的正则表达式来删除尾随字符。

You can use a similar regex to remove trailing chars.

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

$表示在字符串末尾

这篇关于如何删除所有前导和尾随标点符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 13:59