Remove all the special characters using java.util.regex

Hi,
How to remove the all the special characters in a String[] using regex, i have the following:-
public class RegExpTest {
     private static String removeSplCharactersForNumber(String[] number) {
          String number= null;
          Matcher m = null;
               Pattern p = Pattern.compile("\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\_\\+\\-\\{\\}\\|\\;\\\\\\'////\\,\\.\\?\\<\\>\\[\\]");
               for (int i = 0; i < number.length; i++) {
               m = p.matcher(number);
               if (m.find()) {
                    number= m.replaceAll("");
               System.out.println("Final Number is:::"+number);
               return number;
          public static void main(String args[]){
               String[] str = {"raghav!@#$%^&*()_+"};
               RegExpTest regExpTest = new RegExpTest();
               regExpTest.removeSplCharactersForNumber(str);
This code is not working and m.find() is "false", here i want the output to be raghav for the entered string array, not only that it should remove all the special characters for a entered string[]. Is there a simple way to do this to remove all the special characters for a given string[]? More importantly the "spaces" (treated as a spl. character), should be removed as well. Please do provide a solution to this.
Thanks

You don't need the find(). Just use the replaceAll() on each element of the String[] i.e.
String[] values = ...
for (int i = 0; i < values.length; i++)
    values[i] = p.matcher(values).replaceAll("");
}I can't understand your regex since the forum software has mangled it but you just need to add a space to the set of chars to remove. When you post code, surround it with CODE tags then the forum software won't mangle it.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • Parsing xhtml using java.util.regex

    I am parsing an XHTML file using the java.util.regex package and I am perplexed at why the following doesn�t work.
    The lines I wish to match are either like this:
    <span class="someclass"><b>Some String.</b></span></td>
    or
    Some String.</td>
    The code I use to try to achieve this is:
    Pattern somePattern = Pattern.compile(".*(<span class=\"someclass\"><b>)?(.*)[.](</b></span>)?</td>.*");
    String s = null;
    while((s = br.readLine()) != null) {
    if(somePattern.matcher(s).matches()) {
    System.out.println("0:" + eventMatcher.group(0));
    System.out.println("1:" + eventMatcher.group(1));
    System.out.println("2:" + eventMatcher.group(2));
    System.out.println("3:" + eventMatcher.group(3));
    I expect to get as output
    0:<span class="someclass"><b>Some String.</b></span></td> 1:<span class="someclass"><b>
    2:Some String
    3:</b></span>
    or
    0:Some String.</td>
    1:null
    2:Some String
    3:null
    depending on which lines provide the match as mentioned above. Instead I get:
    0:<span class="someclass"><b>Some String.</b></span></td>
    1:null
    2:(empty string)
    3:</b></span>
    or
    0:Some String.</td>
    1:null
    2:(empty string)
    3:null
    Any ideas? Thanks in advance.

    Consider the terms of ".*(<span class=\"someclass\"><b>)?(.*)[.](</b></span>)?</td>.*"
    .* - greedily collect characters
    (<span class=\"someclass\"><b>)? - optionallly collect information taht will always be matched by the previous .* pattern so will be empty.
    (.*) - greedily collect characters that will also have been swallowed by the first .* so will be empty
    [.] - a single .
    (</b></span>)? - optionally collection
    </td> - must be there
    .* - collect the rest of the charcters in the line.
    Therefore in general groups 1 and 2 will be empty because the first .* will have collected the information you wanted to capture!
    You could just make the first .* non-greedy by using .*? but this may fail for other reasons.
    So, in general terms, what are you trying to extract?

  • How to check special characters in java code using Java.util.regex package

    String guid="first_Name;Last_Name";
    Pattern p5 = Pattern.compile("\\p{Punct}");
    Matcher m5 =p5.matcher(guid);
    boolean test=m5.matches();
    I want to find out the weather any speacial characters are there in the String guid using regex.
    but above code is always returning false. pls suggest.

    Pattern.compile ("[^\\w]");The above will match any non [a-zA-Z0-9_] character.
    Or you could do
    Pattern.compile("[^\\s^\\w]");This should match anything that is not a valid charcter and is not whitespace.

  • How can I use java.util.Date and change display format.

    Hello All,
    I want to use java.util.Date in View Context and in Custom Control Context of Web dynpro java. When i mapped of a Input Field to the java.util.Date then message shows that its not supported. Plz suggest me how to handle Date with different formats ??

    If you always want the user to enter the date in dd/MM/yyyy, you can do the following.
    Goto Local Dictonary -> Simple types in your project and create a type known as "InputDate" (or whatever you feel) of built-in type 'Date'.
    Now specifiy its format in the 'Representation' tab as "dd/MM/yyyy" (case-senstive).
    Now declare a value attribute say "inputdate" in your context with this type and bind the inputfield to this context value attribute.
    This will solve your problem.
    But if you want the user to input date depending on the region he belongs, change the default locale date in Control Panel->Regional and Language Options->Change to English(UK) -> Customize -> Date Tab -> Sort Date Format to dd/MM/yyyy.
    Now clear the cache, delete temporary files and restart the machine. This should solve the problem.

  • How to identify the special characters

    Hi all,
    is there any way to identify all the special characters that are already in the various columns of a table,
    thanks
    db is on 8i
    Edited by: venkata_sudheer on Apr 3, 2009 8:44 AM

    Hello,
    I don't know what's your requriment is and how do you want to handle or treat these special characters but check this function, you can pass special character and it will return back the number or you can extend this function to do the reverse (chr(37) 37=%).
    CREATE OR REPLACE FUNCTION ascii_only (p_txt IN VARCHAR2)
       RETURN VARCHAR2
    IS
       v_number   NUMBER;
       v_char     VARCHAR2 (3 BYTE);
    BEGIN
       v_char := SUBSTR (p_txt, 1, 1);
       v_number := (ASCII (v_char));
       DBMS_OUTPUT.put_line (v_number || ':' || v_char);
       RETURN v_number;
    END;
    /Regards

  • Patters for avoiding the '/' (in java.util.regex)

    Hi all ,
    i wanted to knw the pattern format (in java.util.regex) for avoiding the '/' at the begenning of a line ....... hope to get the best answers ....
    thnx 'n cheers
    max

    first of thnx for the quick responses .... !
    what i am really trying to do here is to avoid all lines which are starting with a comment ( '//' or '/*' ) .
    -> I am checking for all lines and inserting a line of code just before a particular statement , the only thing is that statement which i am looking for should not be inside a comment ( '//' or '/*' ) .... hope u got the thing
    thnx
    max

  • Ignore word (Java.util.regex )

    Hello All,
    Can anyone help me to solve this probelm:
    Probelm: I have a text file and i want to search a word or combination of words in that using java.util.regex
    Example : in the sentence "things like the Forestry in the Commission (FC)." i want to search "Forestry Commission" while ignoring the word "in the". This ignoring criteria is specific i.e. search return true only if it ignore "in the" word not any other word.
    Also how i ignore multiple words in ignore condition.
    Thanks in advance.

    Try out this line of code:
    System.out.println("Forestry in the Commission".replaceAll("Forestry\\s(.*?\\s)?Commission", "Hello"));In EBNF, it looks like this:
    match ::= "Forestry" <whitespace> [<character> <whitespace>] "Commission"
    whitespace ::= <space> | \t | \n | \x0B | \f | \r
    character ::= (any one character)
    This, of course, is an ambiguous EBNF definition. The breakdown of the expression, however, reveals why this works. In the string, "\\s" refers to a character of whitespace. "(.*?\\s)?" is where the magic happens: it causes ".*?\\s" to happen either not at all or once. ".*?" will consume as few "." (any character) as possible to make the match, and the following "\\s" is to make sure that strings like "Forestry deCommission" don't match. The EBNF's ambiguity comes from EBNF's lack of ability to describe "reluctant qualifiers": qualifiers that indicate that as few of the given expression should be matched as possible.
    Cheers!

  • Please help on java.util.regex.*

    Hi all,
    My RTF file looks like this:
    Project Num\tab N/A
    \par Project Name\tab Hook-up Installation and Service
    \par
    My intension is to read the file until the \tab and store Project Num as a string into a
    variable. Similarly read until \par and store the value of Project Num into another variable.
    So that i can use those variables further in my program.
    I used java.util.regex.* package for this purpose. I could successfully split the sentence whenever it sees \tab and \par but don't know how to get the text before and after the delimeters and store them into variables.
    The code which i wrote is:
    import java.util.regex.*;
    import java.io.*;
    import java.nio.*;
    import java.nio.charset.*;
    import java.nio.channels.*;
    public class RegexDemo{
    public static void main(String[] args){
    // Create a pattern to match breaks
    Pattern p = Pattern.compile("\\\\.[a-z][a-z]",Pattern.DOTALL);
    try{
    File file = new File("sample.rtf");
    FileInputStream fis = new FileInputStream(file);
    FileChannel fc = fis.getChannel();
    // Get a CharBuffer from the source file
    ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int)fc.size());
    Charset cs = Charset.forName("8859_1");
    CharsetDecoder cd = cs.newDecoder();
    CharBuffer cb = cd.decode(bb);
    // Run some matches
    Matcher m = p.matcher(cb);
    while (m.find())
    System.out.println("Found comment: "+m.group());
    }catch(Exception e){
         e.printStackTrace();
    Please somebody help me in this regard. I have spent lot of time searching the forums but couldn't find any solution.
    Thanks in advance
    rnallu

    Just put target inside parenthesis with delimiters at boundaries.
    Example: "(\\w+)\\t(\\d)\\s" will match occurrences of a word followed with a tab char then a digit followed with a whitespace. If target string matches pattern then m.group(1) contains the word and m.group(2) contains the digit.

  • Doubt in Regular Expressions : java.util.regex

    I want to identify words starting with capital letters in a sentence and I want to replace the matched word with "#" added in front of it.... For example, if my input sentence is
    "Christopher Williams asked Mike Muller a question"
    my output should be,
    "#Christopher #Williams asked #Mike #Muller a question"
    How do I do that using java.util.regex ?
    In perl we can can use *"back references"* in *"replacement string"* . Perl replacement accepts back references whereas java replacement method accepts only strings....
    Please help me.....

    Your replacement is swallowing the space before the uppercase character, and won't match at the beginning of the line.
    Also, it's unnecesarily verbose. String has a replaceAll method (that calls the same methods of Pattern and Matcher under the covers)sentence = s.replaceAll("(^| )([A-Z])", "$1#$2");Disclaimer: I'm no prome, sabre or u/a :-) That can probably be simplified.
    db

  • When I delete files on a USB, it doesn't free up memory on the stik. I find I have to empty the entire stik, use Disk Utility to 'erase' it, then transfer back the files I removed to free up all the space on the stik. Is this the best practice?

    It frustrates me that if I delete a file from a USB, it doesn't free up the memory on the stik. I have been removing all the files from the stik, opening Disk Utility and erasing the empty USB. That frees up the entire stik. Then I have been transferring back the files I removed from the stik. The result is that I have memory available to use again. It seems to me this is an unnecessarily complicated and time consuming way to get the result. Is there a shorter way to do this?

    Hello Horst,
    Thank you for the question.  Have you been emptying your trash after deleting the items?  For the item to be removed from your USB device, you will need to empty the trash on your MacBook Pro after you delete the items, as described in the featured discussion below.  Your USB device will still need to be connected when you do this:
    Choose Empty Trash from the Finder menu. Unlike Windows, the trash needs to be emptied manually for any drive other than one mounted through the network.
    Can't delete off my USB drive
    https://discussions.apple.com/thread/1946841
    Thank you for using Apple Support Communities.
    Best,
    Sheila M.

  • How to escape or remove the special characters in the xml element by regula

    Hi members,
    How to escape or remove the special characters in the xml element by regular expression  in java??
    For Example ,
    <my:name> aaaa </my:name>
    <my:age> 27 </my:age>
    In the above example , i have to retrieve the value of the <my:name> Element(For examlpe -- i have to get "aaaa" from <my:name> tag)...
    How to retreive this value by using DOM with XPATH in java
    Thanks in Advance

    Hi members,
    I forget to paste my coding for the above question....This is my coding......In this display the error...... Pls reply ASAP.......
    PROGRAM:
    import java.io.IOException;
    import java.util.Hashtable;
    import java.util.Map;
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;
    import javax.xml.parsers.*;
    import javax.xml.xpath.*;
    public class DOMReaderForXMP {
         static Document doc;
         static XPath xpath;
         static Object result;
         static NodeList nodes;
         public DOMReaderForXMP() throws ParserConfigurationException, SAXException,
                   IOException, XPathExpressionException {
              DocumentBuilderFactory domFactory = DocumentBuilderFactory
                        .newInstance();
              domFactory.setNamespaceAware(true);
              DocumentBuilder builder = domFactory.newDocumentBuilder();
              doc = builder.parse("d:\\XMP.xml");
              XPathFactory factory = XPathFactory.newInstance();
              xpath = factory.newXPath();
         public static void perform(String path) throws Exception {
              result = xpath.evaluate(path, doc, XPathConstants.NODESET);
              nodes = (NodeList) result;
         public void check() throws Exception {
              perform("//my:name/text()");
              if (!nodes.item(0).getNodeValue().equals("application/pdf")) {
                   System.out.println("Mathces....!");
    ERROR:
    Exception in thread "main" net.sf.saxon.trans.StaticError: XPath syntax error at char 9 in {/my:name}:
    Prefix aas has not been declared

  • How to  remove the Special characters like @,#,$ ,..from field

    How to  remove the Special characters like @,#,$<,..from text  field. we nedd to remove any specila char from text field .
    ex:text  = just#fi%cation@text
    the text should be justification.

    hi check this ..
    data:char(25) value '5#4#2#&1#&',
         char1(9) .
           replace all occurrences of '#' in char with 'and' .
           replace all occurrences of '&' in char with 'num' .
         write: char.
    or use this..
    data:char(25) value 'test@ing*5#4#2#&1#&',
         char1(9) .
           replace all occurrences of '#' in char with space .
           replace all occurrences of '&' in char with space .
           replace all occurrences of '@' in char with space .
           replace all occurrences of '*' in char with space .
         write: char.
    regards,
    venkat.

  • What's wrong with the built-in keyboard on my macbook? The caps button does not work rite, no matter what letter button i push they all come out capitals and the number keys when pushed display the special characters instead of the numbers!

    the built-in keyboard on my macbook is not functioning right, the number keys when pushed display the special characters instead of the numbers,
    the caps button doesn't work at all, the letter buttons display capitals when pushed whether the caps button is on or off, the shift keys are also out of whack!!
    It seems it somehow got relocated to the "0" button because if you push and hold the zero button down the keyboard seems to operate normally, the number keys display numbers when pushed the letter keys display lower case when pushed but release the zero button and your back in the twilight zone!! Can anybody help me resolve this issue? one more thing im using an external usb keyboard right now and it seems to function properly if that helps any.

    You would do better in the actual macbook pro forums (this is not).

  • Hi,   My photo stream used to work fine.  But after removing all the photos to separate folders in my computer, my new photos are no longer streaming to my PC.  They appear in the photo stream on my other devices - iPhone5 and iPad Mini.  It's just my PC

    Hi,
    My photo stream used to work fine.  But after removing all the photos to separate folders in my computer, my new photos are no longer streaming to my PC.  They appear in the photo stream on my other devices - iPhone5 and iPad Mini.  It's just my PC that's missing the photos.
    When I open the iCloud control panel, I cannot turn on the photos.  That option is ghosted.  I'm running on Windows 7 with iCloud 3.0.  Any ideas on how I can fix this?  All help is appreciated!  Thanks!

    Hi Kevinmvb,
    Welcome to the Support Communities!
    The article below may be able to help you with this.  It sounds like you may have moved your photos out of the Uploads folder where they need to reside.
    iCloud: My Photo Stream troubleshooting
    http://support.apple.com/kb/TS3989
    Cheers,
    - Judy

  • Using devanagari script in the 'special characters' option in Pages

    Using the special characters menu in Pages how can I produce double consonances?  Any help would be gratefully received

    That should be double consonants if you have been searching.
    What keyboard are you using?
    Devanāgarī Typing & Keyboard Layouts (Mac & Windows)
    http://www.indiantypefoundry.com/help/technical-issues/devanagari-keyboard/
    https://discussions.apple.com/thread/3548952?start=0&tstart=0
    Peter

Maybe you are looking for

  • Create Accounting when completed in warning the output is coming in XML

    Hello to all, I am having APPS version 12.1.3 OS version OEL 5.5 my problem is that when i am running Create Accounting concurrent request if it completes in warning the output (view output) is coming in XML in browser where as if its completing norm

  • Problem in approval of a sc whose requisitioner has been delimited

    Hi all , The spend limit approver of a shopping cart is not able to approve the SC although it is there in his inbox.He is getting an error ("Error while processing your request ").The requistioner was delimited after he had accepted the changes from

  • ALV Interactive

    Hi, 1)In ALV, how many secondary lists we can have and how ? 2) In upgradation project (for example from 4.6c to Mysap ECC 6.0 version), what are the tools we use to find the object/objects to be upgrated? thnaks in advance Jana

  • Applying parent keywords

    How do I automatically apply parent keywords in Lightroom 3? Apparently there's a setting in Keyword Preferences, but I can't locate Keyword Preferences anywhere in the Library module.

  • Why do people sometimes only receive part of my text message

    I'm wondering if anyone has a solution for this issue?? It happens with several different contacts of mine. I send them a text message of varying sizes and sometimes they only get part of it. I've asked my carrier for support but it isn't a carrier i