正则表达式用于在引号括起时删除字符串中的逗号 [英] Regex for removing comma in a String when it is enclosed by quotes

查看:375
本文介绍了正则表达式用于在引号括起时删除字符串中的逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要用引号括起来删除字符串中的逗号。



例如:

 字符串a =123,\Anders,Jr。\,John,john.anders @ company.com,A


 字符串a =123, Anders Jr.,John,john.anders @ company.com,A

你能不能给我样本java代码这样做?



非常感谢,



Lina

解决方案

可能非常无效,但似乎有效。

  import java.util.regex中*。 

StringBuffer ResultString = new StringBuffer();

try {
Pattern regex = Pattern.compile(。(。*)\(。*),(。*)\(。*),Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(a);
while(regexMatcher.find()){
try {
//你可以随时改变每场比赛的替换文字
regexMatcher.appendReplacement(ResultString, $ 1 $ 2 $ 3 $ 4\" );
} catch(IllegalStateException ex){
// appendReplacement()调用而没有事先成功调用find()
} catch(IllegalArgumentException ex){
//语法错误替换文本(未转义$标志?)
} catch(IndexOutOfBoundsException ex){
//不存在的反向引用使用替换文本
}
}
regexMatcher。 appendTail(ResultString);
} catch(PatternSyntaxException ex){
//正则表达式中的语法错误
}


I need to remove commas within a String only when enclosed by quotes.

example:

String a = "123, \"Anders, Jr.\", John, john.anders@company.com,A"

after replacement should be

String a = "123, Anders Jr., John, john.anders@company.com,A"

Can you please give me sample java code to do this?

Thanks much,

Lina

解决方案

Probably grossly inefficiënt but it seems to work.

import java.util.regex.*;

StringBuffer ResultString = new StringBuffer();

try {
    Pattern regex = Pattern.compile("(.*)\"(.*),(.*)\"(.*)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
    Matcher regexMatcher = regex.matcher(a);
    while (regexMatcher.find()) {
        try {
            // You can vary the replacement text for each match on-the-fly
            regexMatcher.appendReplacement(ResultString, "$1$2$3$4");
        } catch (IllegalStateException ex) {
            // appendReplacement() called without a prior successful call to find()
        } catch (IllegalArgumentException ex) {
            // Syntax error in the replacement text (unescaped $ signs?)
        } catch (IndexOutOfBoundsException ex) {
            // Non-existent backreference used the replacement text
        } 
    }
    regexMatcher.appendTail(ResultString);
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
}

这篇关于正则表达式用于在引号括起时删除字符串中的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆