开发者

Regular Expression using User String

开发者 https://www.devze.com 2023-02-12 07:24 出处:网络
I want to convert an incoming user string into a r开发者_运维技巧egular expression, and the incoming string may contain whitespace. Is there a way to ignore all whitespace within the string?@Zach L an

I want to convert an incoming user string into a r开发者_运维技巧egular expression, and the incoming string may contain whitespace. Is there a way to ignore all whitespace within the string?


@Zach L and @smas answered your real question

I want to convert an incoming user string into a regular expression ...

I want to warn you to be cautious. It is easy to write a pathological regex that can consume vast amounts of CPU time for certain input strings. If you allow users to enter arbitrary regexes themselves, there is a risk that they will enter a pathological regex, either by accident, or with the intention of overloading your service ...


You may be interested in using the COMMENTS flag in the Pattern class, which:

Permits whitespace and comments in pattern. In this mode, whitespace is ignored, and embedded comments starting with # are ignored until the end of a line.

You can find more info on using flags with Patterns here.

An alternative is to just remove the whitespace before compiling your regex by using either String.replace or String.replaceAll.


Maybe something like this will be good to you:

Pattern p = Pattern.compile("...", Pattern.COMMENTS)

Pattern.COMMENTS means:

Permits whitespace and comments in pattern. In this mode, whitespace is ignored, and embedded comments starting with # are ignored until the end of a line.


Use a regular expression replacement (see http://forums.devx.com/showthread.php?t=145832) to remove the spaces. If you are converting user input to a regular expression, be very careful about escaping (it is like SQL is that users can put in metacharacters that will make your program misbehave); you can get information on proper escaping here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号