Java Regexp模式有双反斜杠,如何以可读格式存储模式 [英] Java Regexp patterns have double backslashes, how to store patterns in readable format

查看:62
本文介绍了Java Regexp模式有双反斜杠,如何以可读格式存储模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用单反斜杠存储模式的便捷方式会很棒。一些解决方法:将其存储在文件中并使用NIO进行读取。缺点:Java EE不允许IO访问。以某种方式存储在JNDI中。也许是java 5的新手 Pattern.LITERAL flag可以帮忙吗?我想使用普通模式字符串,例如 \d ,而不是 \\\\

Would be great to have convenient way of storing patterns with single backslash. Some workarounds: store it in the file and use NIO to read. Cons: Java EE does not allow IO access. Store somehow in JNDI. Maybe new to java 5 Pattern.LITERAL flag can help? I want to work with normal pattern string, like \d, not \\d.

推荐答案

麻烦的是, \ 是java中创建时的特殊字符字符串,无论是否正则表达式。

the trouble is that \ is a special char in java when creating a String, regardless of regexp or not.

例如字符串s =\ t;

你不能将它用于任意字符,字符串s =\ a; 会给你一个编译时错误。有效字符是b,t,n,f,r,,和\

you cannot use this for arbitrary chars though, String s = "\a"; will give you a compile-time error. the valid chars are b, t, n, f, r, ", ' and \

因此要获得文字 \ 在java中的字符串中你需要像这样转义: \\ 。因此,你的选项是在java文件中没有这些字符串,因此在你的java文件加载的外部文件中。 Pattern.LITERAL 根本不需要帮助,因为你仍然需要一个有效的java字符串, \d 不是。

therefore to get a literal \ in a string in java you need to escape it like so : \\. because of that, your only option is to NOT have these strings in java files, hence in an external file that is loaded by your java file. Pattern.LITERAL won't help at all because you still need a valid java string, which \d isn't.

这篇关于Java Regexp模式有双反斜杠,如何以可读格式存储模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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